LinkedList

LinkedList - / Assignment #: 10 / Name: greg ossman /...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
// Assignment #: 10 // Name: greg ossman // StudentID: 1201651325 // Lecture: MWF 1045 // Description: A linked list is a sequence of nodes with efficient // element insertion and removal. This class contains a subset of the methods of the // standard java.util.LinkedList class. import java.util.NoSuchElementException; public class LinkedList { //nested class to represent a node private class Node { public Object data; public Node next; } //only instance variable that points to the first node. private Node first; // Constructs an empty linked list. public LinkedList() { first = null; } // Returns the first element in the linked list. public Object getFirst() { if (first == null) { NoSuchElementException ex = new NoSuchElementException(); throw ex; } else return first.data; } // Removes the first element in the linked list. public Object removeFirst() { if (first == null) { NoSuchElementException ex = new NoSuchElementException(); throw ex; } else { Object element = first.data; first = first.next; //change the reference since it's removed. return element; } }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
// Adds an element to the front of the linked list. public void addFirst(Object element) { //create a new node Node newNode = new Node(); newNode.data = element; newNode.next = first; //change the first reference to the new node. first = newNode; } // Returns an iterator for iterating through this list. public ListIterator listIterator() { return new LinkedListIterator(); } // returns a string containing all elements of the Linked list public String toString() { ListIterator iterator = listIterator(); String result= "{ "; while(iterator.hasNext()==true) { result+=iterator.next()+" "; } result+="}\n"; return result; } //The size method returns the number of objects in the linked list using list iterator public int size()
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/21/2011 for the course CSE 205 taught by Professor Matasu during the Spring '08 term at ASU.

Page1 / 7

LinkedList - / Assignment #: 10 / Name: greg ossman /...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online