LinkedList - /Assignment 2/Name Johrdyn Lorden/StudentID...

This preview shows page 1 - 3 out of 8 pages.

//Assignment #: 2//Name: Johrdyn Lorden//StudentID: 1201666366// Lecture: MWF 1:30pm//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.*;public class LinkedList{//nested class to represent a nodeprivate 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;}elsereturn 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;}}// Adds an element to the front of the linked list.public void addFirst(Object element){//create a new nodeNode 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 iteratorprivate class LinkedListIterator implements ListIterator{private Node position; //current positionprivate Node previous; //it is used for remove() method// Constructs an iterator that points to the front// of the linked list.public LinkedListIterator(){position = null;previous = null;}// Tests if there is an element after the iterator position.public boolean hasNext(){if (position == null) //not traversed yet{if (first != null)return true;elsereturn false;}else{if (position.next != null)return true;elsereturn false;}}

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture