double-linked lists and circular lists

Download Double-Linked Lists and Circular Lists

Post on 22-Feb-2016




0 download

Embed Size (px)


Double-Linked Lists and Circular Lists. Double-Linked Lists. Limitations of a singly-linked list: Insertion at the front is O(1) insertion at other positions is O( n ) Insertion is convenient only after a referenced node Removing a node requires a reference to the previous node - PowerPoint PPT Presentation


PowerPoint Presentation

Double-Linked Lists and Circular ListsCS3401

Double-Linked ListsLimitations of a singly-linked list:Insertion at the front is O(1)insertion at other positions is O(n)Insertion is convenient only after a referenced nodeRemoving a node requires a reference to the previous nodeWe can traverse the list only in the forward directionHow to overcome these limitations?Double-linked listCS3402Double-Linked Lists (cont.)CS3403

Node Classprivate static class Node { private E data; private Node next = null; private Node prev = null;

private Node(E dataItem) { data = dataItem; }}CS3404

Inserting into a Double-Linked List5next = = prevdata = "Harry"Nodenext = null = prevdata = "Sam"Nodenext = = prevdata = "Sharon"NodeNode sharon = new Node("Sharon"); = sam; sharon.prev = sam.prev; = sharon;sam.prev = sharon;from predecessorto predecessorsamsharonRemoving from a Double-Linked ListCS3406next = = prevdata = "Dick"Nodenext = = prevdata = "Harry"Nodenext = = prevdata = "Sharon" = = harry.prevA Double-Linked List ClassA double-linked list object has data fields:head (a reference to the first list Node)tail (a reference to the last list Node)size Insertion at either end is O(1)Insertion elsewhere is still O(n)


The LinkedList Class and the Iterator, ListIterator, and Iterable Interfaces

CS3408The LinkedList ClassCS3409

The IteratorA moving place marker Iterator object for a list starts at the list headIt can move by calling its next method.Stays on its current list item until it is needed An Iterator traverses in O(n) while a list traversal using get() calls in a linked list is O(n2)CS34010Iterator InterfaceDefined in java.utilCS34011

The List interface declares the method iterator which returns an Iterator object that iterates over the elements of that list

11Iterator Interface (cont.)An Iterator is between elementsCS34012

Iterator Interface (cont.)In the following loop, we process all items in List through an Iterator

Iterator iter = aList.iterator();while (iter.hasNext()) { int value =; // Do something with value ...}

CS34013Iterators and Removing Elementsremove() deletes the most recent element returnedYou must call next()before each remove()Else IllegalStateException will be thrownLinkedList.remove vs. Iterator.remove:LinkedList.remove must walk down the list each time, then remove, O(n2) complexityIterator.remove removes items without starting over at the beginning, O(n) complexityCS34014Explain to your neighbor why these complexities14Iterators and Removing Elements (cont.)Remove all elements from a list of type Integer that are divisible by a particular value:

public static void removeDivisibleBy(LinkedList aList, int div) { Iterator iter = aList.iterator(); while (iter.hasNext()) { int nextInt =; if (nextInt % div == 0) { iter.remove(); } }}CS34015ListIterator InterfaceIterator limitationsTraverses List only in the forward directionProvides a remove method, but no add methodIf you do not want to start from the beginning:You must advance the Iterator using your own loopSolution:ListIterator extends IteratorCS34016ListIterator Interface (cont.)ListIterator is positioned between elements of the listListIterator positions: 0 to size


ListIterator Interface (cont.)18

ListIterator Interface (cont.)CS34019

Which one is more general? Convince your neighbor19Comparison of Iterator and ListIteratorListIterator is a subinterface of IteratorClasses that implement ListIterator must provide the features of bothIterator:Requires fewer methodsCan iterate over more general data structuresIterator is required by the Collection interfaceListIterator is required only by the List interfaceCS34020Conversion Between ListIterator and an IndexListIterator:nextIndex()returns the index of item to be returned by next()previousIndex() returns the index of item to be returned by previous()LinkedList has method listIterator(int index) Returns a ListIterator positioned so next()will return the item at position indexHow? What is the complexity?CS34021The listIterator (int index) method creates a new ListIterator that starts at the beginning, and walks down the list to the desired position generally an O(n) operation

21Conversion Between ListIterator and an Index (cont.)CS34022

The listIterator (int index) method creates a new ListIterator that starts at the beginning, and walks down the list to the desired position generally an O(n) operation

22Implementation of a Double-Linked List ClassCS34023


CS340LinkedList (cont.)import java.util.*;

/** Class CS340LinkedList implements a double linked list and a ListIterator. */

public class CS340LinkedList { // Data Fields private Node head = null; private Node tail = null; private int size = 0; . . .25Add MethodObtain a reference, nodeRef, to the node at position indexInsert a new Node containing obj before the node referenced by nodeRefTo use a ListIterator object to implement add:Obtain an iterator that is positioned just before the Node at position indexInsert a new Node containing obj before the Node currently referenced by this iterator/** Add an item at the specified index. @param index The index at which the object is to be inserted @param obj The object to be inserted @throws IndexOutOfBoundsException if the index is out of range (i < 0 || i > size())*/public void add(int index, E obj) { listIterator(index).add(obj);}26It is not necessary to declare a local ListIterator; the method call listIterator returns an anonymous ListIterator object

26Get MethodObtain a reference, nodeRef, to the node at position indexReturn the contents of the Node referenced by nodeRef/** Get the element at position index. @param index Position of item to be retrieved @return The item at index*/public E get(int index) { return listIterator(index).next();}CS34027Other Add and Get Methodspublic void addFirst(E item) { add(0, item);}public void addLast(E item) { add(size, item);} public E getFirst() { return;} public E getLast() { return;}CS34028Implementing the ListIterator InterfaceCS340ListIter is an inner class of CS340LinkedList which implements the ListIterator interface


Implementing the ListIterator Interface (cont.)private class CS340ListIter implements ListIterator { private Node nextItem; private Node lastItemReturned; private int index = 0; ...CS34030Constructor31public CS340ListIter(int i) { if (i < 0 || i > size) { // Validate i parameter. throw new IndexOutOfBoundsException("Invalid index " + i); } lastItemReturned = null; // No item returned yet. if (i == size) {// Special case of last item index = size; nextItem = null; } else { // Start at the beginning nextItem = head; for (index = 0; index < i; index++) { nextItem =; } }}The hasNext()Methodtests to see if nextItem is nullpublic boolean hasnext() {return nextItem != null;}

CS34032Advancing the Iterator33CS340LinkedListhead tail size 3next prev nulldata "Tom"Nodenext prev

Nodenext prevdata "Sam"Nodepublic E next() { if (!hasNext()) { throw new NoSuchElementException(); } lastItemReturned = nextItem; nextItem =; index++; return;}CS340ListIter nextItem lastItemReturned index 12data "Harry"Why is the iterator useful?Process all elements of a listfor(i=0; i < aList.size(); i++){E nextElement = aList.get(i);}

E get(int index){Node nodeRef = head;for(i=0; i < index; i++){nodeRef =;}}CS34034Why is the iterator useful? (cont.)Process all elements of a listfor(i=0; i < aList.size(); i++){E nextElement = listIterator(i).get();}CS34035Previous Methodspublic boolean hasPrevious() { return (nextItem == null && size != 0) || nextItem.prev != null;}public E previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } if (nextItem == null) { // Iterator past the last element nextItem = tail; } else { nextItem = nextItem.prev; } lastItemReturned = nextItem; index--; return;}

36The Add Method4 cases to address:Add to an empty listAdd to the head of the listAdd to the tail of the listAdd to the middle of the listCS34037Adding to an Empty ListCS34038if (head == null) { head = new Node(obj); tail = head;}...size++(after insertion)CS340ListIter nextItem = lastItemReturned = null index = 01CS340LinkedListhead = nulltail = nullsize = 31Nodenext =null = prevdata = "Tom"39 Adding to the Head of the ListNodenext =null = prevdata = "Tom"CS340ListIter nextItem = lastItemReturned = null index = 0if (nextItem == head) { Node newNode = new Node(obj); = nextItem; nextItem.prev = newNode; head = newNode;}...size++;index++;CS340LinkedListhead = nulltail = nullsize = 31Nodenext = = prevdata = "Harry"Nodenext = null = prevdata = "Sam"4next = nullnull = prevdata = "Ann"NodenewNode40Adding to the Tail of the ListNodenext =prev = nulldata = "Tom"CS340ListIter nextItem = nulllastItemReturned = null index = 2if (nextItem == null) { Node newNode = new Node(obj); = newNode; newNode.prev = tail; tail = newNode}...size++;index++;CS340LinkedListhead = nulltail = nullsize = 33Nodenext = = prevdata = "Ann"Nodenext = null = prevdata = "S


View more >