© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for...

57
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java Data Structures for Java William H. Ford William H. Ford William R. Topp William R. Topp Chapter 11 Chapter 11 Implementing the LinkedList Implementing the LinkedList Class Class Bret Ford © 2005, Prentice Hall

Transcript of © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for...

Page 1: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Data Structures for JavaData Structures for JavaWilliam H. FordWilliam H. FordWilliam R. ToppWilliam R. Topp

Chapter 11Chapter 11

Implementing the LinkedList Implementing the LinkedList ClassClass

Bret Ford

© 2005, Prentice Hall

Page 2: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Singly Linked ListsSingly Linked Lists Singly-linked lists provide efficient Singly-linked lists provide efficient

insertion and deletion at the front of insertion and deletion at the front of the list. Inserting at the back of a the list. Inserting at the back of a singly-linked list is inefficient, singly-linked list is inefficient, because it requires a linear scan that because it requires a linear scan that determines the back of the list.determines the back of the list.

Page 3: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode ObjectsDNode Objects A DNode object has reference fields A DNode object has reference fields

to both the previous node and the to both the previous node and the next node in the list.next node in the list.

A sequence of DNode objects creates A sequence of DNode objects creates a list called aa list called a doubly-linked list doubly-linked list..

Page 4: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode ClassDNode Class A DNode object has a variableA DNode object has a variable

nodeValue that stores the value and nodeValue that stores the value and two other variables, prev and next, two other variables, prev and next, that reference the predecessor and that reference the predecessor and successor of the node, respectively.successor of the node, respectively.

The DNode class is similar to the The DNode class is similar to the Node class. It has public data that Node class. It has public data that simplifies access when building simplifies access when building implementation structures.implementation structures.

Page 5: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode Class (continued)DNode Class (continued)

The class has two constructors. The The class has two constructors. The default constructor creates a DNode default constructor creates a DNode object with the nodeValue field set to object with the nodeValue field set to null. The second constructor provides null. The second constructor provides an argument of type Object to an argument of type Object to initialize nodeValue.initialize nodeValue.

Page 6: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode Class (continued)DNode Class (continued)public class DNode<T>{ public T nodeValue; // data value of the node public DNode<T> prev; // previous node in the list public DNode<T> next; // next node in the list // default constructor; creates an object with // the value set to null and whose references // point to the node itself public DNode() { nodeValue = null; // the next node is the current node next = this; // the previous node is the current node prev = this; }

Page 7: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode Class (continued)DNode Class (continued)

// creates object whose value is item and // whose references point to the node itself public DNode(T item) { nodeValue = item; // the next node is the current node next = this; // the previous node is the current node prev = this; }}

Page 8: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNode Class (concluded)DNode Class (concluded) The declaration of each constructorThe declaration of each constructor

uses the reference uses the reference thisthis to initialize to initialize the links next and prev. The keyword the links next and prev. The keyword this is a reference to the object itself. this is a reference to the object itself. The effect is to have each The effect is to have each constructor create a node with links constructor create a node with links that point back to itself.that point back to itself.

Page 9: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node in a Doubly Inserting a Node in a Doubly Linked ListLinked List

Inserting a Node At a PositionInserting a Node At a Position Assume the insertion occurs at Assume the insertion occurs at

reference location curr.reference location curr. Four reference fields in the new node, in Four reference fields in the new node, in

node curr, and in node prevNode node curr, and in node prevNode (curr.prev) must be updated. (curr.prev) must be updated.

Page 10: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node in a Doubly Inserting a Node in a Doubly Linked List (continued)Linked List (continued)

// declare the DNode reference variables newNode and prevNodeDNode<T> newNode, prevNode;// create a new node and assign prevNode to reference the// predecessor of currnewNode = new DNode<T>(item);prevNode = curr.prev; // update reference fields in newNodenewNode.prev = prevNode; // statement 1newNode.next = curr; // statement 2

// update curr and its predecessor to point at newNodeprevNode.next = newNode; // statement 3curr.prev = newNode; // statement 4

Page 11: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node in a Doubly Inserting a Node in a Doubly Linked List (concluded)Linked List (concluded)

Page 12: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Deleting a Node in a Doubly Deleting a Node in a Doubly Linked ListLinked List

Deleting a node at a position.Deleting a node at a position. Assume the deletion occurs at reference Assume the deletion occurs at reference

location curr.location curr. The algorithm involves unlinking the node The algorithm involves unlinking the node

from the list by having the predecessor of from the list by having the predecessor of curr and the successor of curr point at curr and the successor of curr point at each other. each other.

Page 13: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Deleting a Node in a Doubly Deleting a Node in a Doubly Linked List (concluded)Linked List (concluded)

DNode<T> prevNode = curr.prev, nextNode = curr.next; // update the reference variables in the adjacent nodes.prevNode.next = nextNode; // statement 1nextNode.prev = prevNode; // statement 2

Page 14: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Circular Doubly Linked ListsCircular Doubly Linked Lists

A doubly-linked list contains aA doubly-linked list contains a sentinel nodesentinel node called header. called header.

The sentinel is a DNode object The sentinel is a DNode object containing a null data value. A containing a null data value. A linked-list algorithm never uses this linked-list algorithm never uses this value.value.

header.next references the first node header.next references the first node of the list, and header.prev of the list, and header.prev references the last node.references the last node.

Page 15: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Circular Doubly Linked Circular Doubly Linked Lists (continued)Lists (continued)

Page 16: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Circular Doubly Linked Lists Circular Doubly Linked Lists (concluded)(concluded)

Traversing a list can begin with the Traversing a list can begin with the header node and continue either header node and continue either forward or backward until the scan forward or backward until the scan returns to the header. returns to the header.

Page 17: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Declaring a Doubly Linked Declaring a Doubly Linked ListList

The declaration of a list begins with The declaration of a list begins with the declaration of the header node.the declaration of the header node.

The default constructor is used to The default constructor is used to create the header node.create the header node.

DNode<T> header = new DNode<T>();

Page 18: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Declaring a Doubly Linked Declaring a Doubly Linked List (continued)List (continued)

The declaration of a singly linked list The declaration of a singly linked list begins by assigning front the value begins by assigning front the value null. The resulting singly-linked list null. The resulting singly-linked list has no nodes.has no nodes.

Empty list: Empty list: front == null A doubly-linked list always contains A doubly-linked list always contains

at least one node, the header.at least one node, the header.Empty list: Empty list: header.next == header

oror header.prev == header

Page 19: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Declaring a Doubly Linked Declaring a Doubly Linked List (concluded)List (concluded)

Page 20: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNodes.toString()DNodes.toString()

public static <T> String toString(DNode<T> header){ if (header.next == header) return "null";

// scan list starting at the first node; // add value to string DNode<T> curr = header.next; String str = "[" + curr.nodeValue;

Page 21: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

DNodes.toString() DNodes.toString() (concluded)(concluded)

// append all but last node, separating // items with a comma // polymorphism calls toString() for the // nodeValue type while(curr.next != header) { curr = curr.next; str += ", " + curr.nodeValue; } str += "]"; return str;}

Page 22: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a NodeInserting a Node The insert operation adds a newThe insert operation adds a new

element at a designated referenceelement at a designated referencelocation in the list, creates a new node and location in the list, creates a new node and adds it to the list immediately before the adds it to the list immediately before the designated node.designated node.

Implemented by addBefore() that takes a Implemented by addBefore() that takes a DNodeDNode reference argument reference argument currcurr and a new and a new value as arguments. The return value is a value as arguments. The return value is a reference to the new node. The algorithm reference to the new node. The algorithm involves updating four links, so the algorithm involves updating four links, so the algorithm has running time O(1).has running time O(1).

Page 23: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node (continued)Inserting a Node (continued)

Page 24: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node (continued)Inserting a Node (continued)public static <T> DNode<T> addBefore(DNode<T>curr, T item){ // declare reference variables for new node // and previous node DNode<T> newNode, prevNode;

// create new DNode with item as initial value newNode = new DNode<T>(item);

// assign prevNode the reference value // of node before p prevNode = curr.prev;

Page 25: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting a Node Inserting a Node (concluded)(concluded)

// update reference fields in newNode newNode.prev = prevNode; newNode.next = curr;

// update curr and prevNode to point at newNode prevNode.next = newNode; curr.prev = newNode;

return newNode;}

Page 26: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inserting into an Empty ListInserting into an Empty List Inserting an element into an empty Inserting an element into an empty

list simultaneously creates both the list simultaneously creates both the first and the last node in the list.first and the last node in the list.

The header can reference this node The header can reference this node by using the by using the header.nextheader.next and the and the link link header.prevheader.prev..

Page 27: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Removing a NodeRemoving a Node The algorithm involves updating links in the The algorithm involves updating links in the

adjacent successor and predecessor nodes.adjacent successor and predecessor nodes. The method The method remove()remove() takes a takes a DNodeDNode

reference reference currcurr as an argument. If curr as an argument. If curr points back to itself (points back to itself (curr.next == currcurr.next == curr), ), currcurr is the header node of an empty list, is the header node of an empty list, and the method simply returns.and the method simply returns.

The update of the links requires only two The update of the links requires only two statements, so remove() has running time statements, so remove() has running time O(1). O(1).

Page 28: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Removing a Node Removing a Node (continued)(continued)

Page 29: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Removing a Node Removing a Node (concluded)(concluded)public static <T> void remove(DNode<T> curr)

{ // return if the list is empty if (curr.next == curr) return;

// declare references for the predecessor // and successor nodes DNode<T> prevNode = curr.prev, nexNode = curr.next;

// update reference fields for // predecessor and successor prevNode.next = nexNode; nexNode.prev = prevNode;}

Page 30: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Modifying the Ends of a ListModifying the Ends of a List

In a singly-linked list, operations that In a singly-linked list, operations that insert or delete nodes at the ends of insert or delete nodes at the ends of the list require very distinct algorithms.the list require very distinct algorithms.

Because a doubly-linked list is a Because a doubly-linked list is a circular list with a header node, update circular list with a header node, update operations at the ends of the list operations at the ends of the list simply use addBefore() and remove() simply use addBefore() and remove() with arguments that are reference with arguments that are reference fields in the header. fields in the header.

Page 31: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Modifying the Ends of a List Modifying the Ends of a List (continued)(continued)

To insert item at the front of the list, To insert item at the front of the list, call call addBefore(header.next, item)addBefore(header.next, item). .

Page 32: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Modifying the Ends of a List Modifying the Ends of a List (continued)(continued)

To remove the front of the list, call To remove the front of the list, call remove(header.next)remove(header.next)..

Page 33: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Modifying the Ends of a List Modifying the Ends of a List (concluded)(concluded)

Update back of list with addBefore() or Update back of list with addBefore() or remove() using header as the argument.remove() using header as the argument.

Page 34: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

jumbleLetters()jumbleLetters()public static String jumbleLetters(String word){ DNode<Character> header = new DNode<Character>(); String jumbleword = "";

// use rnd.nextInt(2) to determine if char // is inserted at the front (value = 0) or // back (value = 1) of list for (int i = 0; i < word.length(); i++) if (rnd.nextInt(2) == 0) // add at the front of the list DNodes.addBefore(header.next,word.charAt(i)); else // insert at the back of the list DNodes.addBefore(header, word.charAt(i));

Page 35: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

jumbleLetters()jumbleLetters()(concluded)(concluded)

// create the jumbled word and clear the list while (header.next != header) { jumbleword += header.next.nodeValue; DNodes.remove(header.next); } return jumbleword;}

Page 36: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 11.1Program 11.1import java.util.Random;import java.util.Scanner;

import ds.util.DNode;import ds.util.DNodes;

public class Program11_1{ static Random rnd = new Random();

public static void main(String[] args) { Scanner keyIn = new Scanner(System.in);

String word, jumbleword; int numWords, i, j;

// prompt for the number of words to enter System.out.print("How many words will you" + " enter? ");

Page 37: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 11.1 (continued)Program 11.1 (continued) numWords = keyIn.nextInt();

for (i = 0; i < numWords; i++) { System.out.print("Word: "); word = keyIn.next(); jumbleword = jumbleLetters(word);

// output the word and its jumbled variation System.out.println("Word/Jumbled Word: " + word + " " + jumbleword); } }

public static String jumbleLetters(String word) { DNode<Character> header = new DNode<Character>(); String jumbleword = "";

Page 38: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 11.1 (concluded)Program 11.1 (concluded) // use rnd.nextInt(2) to determine if char // is inserted at the front (value = 0) or // back (value = 1) of list for (int i = 0; i < word.length(); i++) if (rnd.nextInt(2) == 0) // add at the front of the list DNodes.addBefore(header.next,word.charAt(i)); else // insert at the back of the list DNodes.addBefore(header, word.charAt(i));

// create the jumbled word and clear the list while (header.next != header) { jumbleword += header.next.nodeValue; DNodes.remove(header.next); } return jumbleword; }}

Page 39: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 11.1 (Run)Program 11.1 (Run)

Run:

How many words will you enter? 3Word: beforeWord/Jumbled Word: before erofebWord: javaWord/Jumbled Word: java vjaaWord: linkWord/Jumbled Word: link knli

Page 40: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Graphical Version ofGraphical Version ofProgram 11.1Program 11.1

Program11_1G.java in Chapter 11 of the Program11_1G.java in Chapter 11 of the software supplement is a graphical version software supplement is a graphical version of Program 11.1. Here is a sample run.of Program 11.1. Here is a sample run.

Page 41: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

LinkedList Class Private LinkedList Class Private MembersMembers

The DNode reference header identifies The DNode reference header identifies the doubly-linked list that stores the the doubly-linked list that stores the elements.elements.

The integer listSize maintains a count of The integer listSize maintains a count of the number of elements in the list.the number of elements in the list.

A class method increments modCount A class method increments modCount whenever its execution updates the list. whenever its execution updates the list. The variable is used in the The variable is used in the implementation of iterators (Chapter 13).implementation of iterators (Chapter 13).

Page 42: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

LinkedList Class Private LinkedList Class Private Members (continued)Members (continued)

Page 43: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

LinkedList Class OutlineLinkedList Class Outlinepublic class LinkedList<T> implements List<T>{ // number of elements in the list private int listSize;

// the doubly-linked list header node private DNode<T> header;

// maintains a count of the number of list updates private int modCount;

< private utility methods >

< constructor, List interface, and special purpose methods >}

Page 44: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Index OperationsIndex Operations For add() and remove() at an index, we For add() and remove() at an index, we

need to first determine if the index is in need to first determine if the index is in range and then identify the reference range and then identify the reference that points to the node at the index that points to the node at the index position. The private methods position. The private methods rangeCheck() and nodeAtIndex() handle rangeCheck() and nodeAtIndex() handle these tasks.these tasks.

rangeCheck() throws an rangeCheck() throws an IndexOutOfBoundsException if an index IndexOutOfBoundsException if an index is not in range.is not in range.

Page 45: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Index Operations Index Operations (continued)(continued)

nodeAtIndex() returns a DNode reference nodeAtIndex() returns a DNode reference that points at position index using a loop that points at position index using a loop from 0 to index that tracks a node from 0 to index that tracks a node reference variable which starts at header reference variable which starts at header and moves forward using the next and moves forward using the next reference field.reference field.

Page 46: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Index Operations Index Operations (concluded)(concluded)// return the DNode reference that points at

// an element at position indexprivate DNode<T> nodeAtIndex(int index){ // check if index is in range rangeCheck(index);

// start at the header DNode<T> p = header;

// go to index either by moving forward // from the front of the list; see // Programming Exercise 11.16 for a way // to improve the performance of this method for (int j = 0; j <= index; j++) p = p.next;

// return reference to node at position p = index return p;}

Page 47: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

LinkedList Class ConstructorLinkedList Class Constructor

// construct an empty listpublic LinkedList(){ header = new DNode<T>(); listSize = 0; modCount = 0;}

Page 48: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Indexed List AccessIndexed List Access The indexed access methods get() and The indexed access methods get() and

set() are implemented by using the set() are implemented by using the private method nodeAtIndex().private method nodeAtIndex().

These methods are not efficient if they are These methods are not efficient if they are used repeatedly in a program, because used repeatedly in a program, because nodeAtIndex() must sequence through the nodeAtIndex() must sequence through the doubly-linked list elements until it reaches doubly-linked list elements until it reaches the node at position index. A LinkedList the node at position index. A LinkedList collection is really designed to be collection is really designed to be accessed sequentially. accessed sequentially.

Page 49: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Indexed List AccessIndexed List Access(concluded)(concluded)

// replaces the value at the specified position// in this list with item and returns the// previous valuepublic T set(int index, T item){ // get the reference that identifies node // at position index DNode<T> p = nodeAtIndex(index);

// save the old value T previousValue = p.nodeValue;

// assign item at position index p.nodeValue = item;

// return the previous value return previousValue;}

Page 50: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Searching a ListSearching a List The method indexOf() takes anThe method indexOf() takes an

argument of type Object and returns argument of type Object and returns the index of the first occurrence of the index of the first occurrence of the target in the list or -1 if it is not the target in the list or -1 if it is not found. It is used by the index-based found. It is used by the index-based add() and remove() methods.add() and remove() methods.

The related method contains() The related method contains() searches the list and returns a searches the list and returns a boolean value. boolean value.

Page 51: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Searching a List (continued)Searching a List (continued)public int indexOf(Object item){ int index = 0;

// search for item using equals() for (DNode<T> curr = header.next; curr != header; curr = curr.next) { if (item.equals(curr.nodeValue)) // success return index; index++; }

// item is not in the list; return -1 return -1;}

Page 52: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Searching a List (concluded)Searching a List (concluded)

// returns true if this list contains// item and false otherwisepublic boolean contains(Object item){ return indexOf(item) >= 0;}

Page 53: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Modifying a ListModifying a List The LinkedList class has various formsThe LinkedList class has various forms

of the add() and remove() methods to of the add() and remove() methods to insert and delete elements in a list. In insert and delete elements in a list. In each case the method must position each case the method must position itself at the appropriate node. Once the itself at the appropriate node. Once the is done, the insertion or deletion is done, the insertion or deletion operation is executed by calling the operation is executed by calling the corresponding private methods corresponding private methods addBefore(curr, item) and remove(curr) addBefore(curr, item) and remove(curr) where curr is the node reference.where curr is the node reference.

Page 54: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Adding to the Back of a ListAdding to the Back of a List The add(T item) method inserts a new The add(T item) method inserts a new

node with value item at the back of the node with value item at the back of the list. Its implementation uses list. Its implementation uses addBefore(header,item)addBefore(header,item) with with headerheader serving as the argument. After serving as the argument. After updating the list size, add() returns updating the list size, add() returns truetrue..

Some Java collections, that also Some Java collections, that also implement the Collection interface, do implement the Collection interface, do not allow duplicate values. For these not allow duplicate values. For these collections, the add() method returns collections, the add() method returns false if false if itemitem is already in the list. is already in the list.

Page 55: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Adding to the Back of a List Adding to the Back of a List (concluded)(concluded)

// appends item to the end of this list// and returns truepublic boolean add(T item){ // insert item at the end of list and // increment list size DNodes.addBefore(header,item); listSize++;

// the list has changed modCount++;

return true;}

Page 56: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Removing at an IndexRemoving at an Index

The remove(int i) method deletes the The remove(int i) method deletes the node at position index in the list and node at position index in the list and returns its value.returns its value.

Locating the node is the task of the Locating the node is the task of the method call nodeAtIndex() which first method call nodeAtIndex() which first uses rangeCheck() to validate the uses rangeCheck() to validate the index or throw an index or throw an IndexOutOfBoundsException. The IndexOutOfBoundsException. The deletion is handled by the private deletion is handled by the private method remove(curr). method remove(curr).

Page 57: © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Removing at an Index Removing at an Index (concluded)(concluded)

public T remove(int index){ DNode<T> p = nodeAtIndex(index);

// save the return value T returnElement = p.nodeValue;

// remove element at node p and decrement list size remove(p); listSize--;

// we've made a modification modCount++;

// return the value that was removed return returnElement;}