LinkedList

LinkedList - / / / / A linked list is a sequence of nodes...

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

View Full Document Right Arrow Icon
// 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; import java.util.IndexOutOfBoundsException; 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(); } //nested class to define its iterator private class LinkedListIterator implements ListIterator { private Node position; //current position private Node previous; //it is used for remove() method // Constructs an iterator that points to the front // of the linked list. public LinkedListIterator()
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 09/20/2009 for the course CSE 205 taught by Professor Matasu during the Spring '08 term at ASU.

Page1 / 6

LinkedList - / / / / A linked list is a sequence of nodes...

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