Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Programming With Java ICS201 Chapter 15 Linked Data Structures 1 Programming With Java ICS201 Linked Data Structures o A linked data structure consists of capsules of data known as nodes that are connected via links. Links can be viewed as arrows and thought of as one way passages from one node to another. o In Java, nodes are realized as objects of a node class. o The data in a node is stored via instance variables. o The links are realized as references. A reference is a memory address, and is stored in a variable of a class type. Therefore, a link is an instance variable of the node class type itself. 2 Programming With Java ICS201 Java Linked Lists o The simplest kind of linked data structure is a linked list. o A linked list consists of a single chain of nodes, each connected to the next by a link. The first node is called the head node. The last node serves as a kind of end marker. Contains a reference to the first node in the linked list. 3 Programming With Java ICS201 A Simple Linked List Class o In a linked list, each node is an object of a node class. Each node is typically illustrated as a box containing one or more pieces of data. o Each node contains data and a link to another node. A piece of data is stored as an instance variable of the node. Data is represented as information contained within the node "box“. Links are implemented as references to a node stored in an instance variable of the node type. Links are typically illustrated as arrows that point to the node to which they "link“. 4 Programming With Java ICS201 Example (Linked List Class) public class Node { private String item ; private int count ; private Node link ; public Node ( ) { link = null ; item = null ; count = 0 ; } public Node ( String newitem , int newCount , Node linkValue) { item = newitem ; count = newCount ; link = linkValue; } ………………………………………………………………………………… } 5 Programming With Java ICS201 A Simple Linked List Class o A linked list object contains the variable head as an instance variable of the class. o A linked list object does not contain all the nodes in the linked list directly. Rather, it uses the variable head to locate the head node of the list. The head node and every node of the list contain a link variable that provides a reference to the next node in the list. Therefore, once the head node can be reached, then every other node in the list can be reached. 6 Programming With Java ICS201 An Empty List Is Indicated by null o The head instance variable contains a reference to the first node in the linked list. If the list is empty, this instance variable is set to null. o The linked list constructor sets the head instance variable to null. This indicates that the newly created linked list is empty. Example: public class LinkedList { private Node head ; public LinkedList ( ) { head = null ; } ………………………………………………………………………………… } 7 Programming With Java ICS201 Indicating the End of a Linked List • The last node in a linked list should have its link instance variable set to null. That way the code can test whether or not a node is the last node. 8 Example (Linked List Class) public class Node { Programming With Java ICS201 private String item ; private int count ; private Node link ; public Node ( ) { link = null ; item = null ; count = 0 ; } public Node ( String newitem , int newCount , Node linkValue) { item = newitem ; count = newCount ; link = linkValue; } public String getItem ( ) { return item ; } public int getCount ( ) { return count ; } public Node getLink ( ) { return link ; } } continued 9 Programming With Java ICS201 Example (Linked List Class) public class LinkedList { private Node head; public LinkedList( ) { head = null; } /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ public void addToStart(String itemName, int itemCount) { head = new Node(itemName, itemCount, head); } /** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.getLink( ) ; return true; } else return false; } continued 10 Programming With Java ICS201 Example (Linked List Class) /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; Node position = head; while (position != null) { count++; position = position.getLink( ); } return count; } public boolean contains(String item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node find(String target) { Node position = head; String itemAtPosition; while (position != null) { itemAtPosition = position.getItem( ); if (itemAtPosition.equals(target)) return position; position = position.getLink( ); } return null; //target was not found } 11 Programming With Java ICS201 Example (Linked List Class) public void outputList( ) { Node position = head; while (position != null) { System.out.println(position.getItem( ) + " “ + position.getCount( )); position = position.getLink( ); } } public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; } } class LinkedListDemo { public static void main(String[] args) { LinkedList list = new LinkedList( ); list.addToStart("Saturday", 1); list.addToStart("Sunday", 2); list.addToStart("Monday", 3); System.out.println("List has " + list.size( ) + " nodes."); list.outputList( ); if (list.contains("Monday")) System.out.println("Monday is on list."); else System.out.println("Monday is NOT on list."); list.deleteHeadNode( ); if (list.contains("Monday")) System.out.println("Monday is on list."); else System.out.println("Monday is NOT on list."); list.clear() ; } } System.out.println("Start of list:"); list.outputList( ); System.out.println("End of list."); Output: List has 3 nodes. Monday 3 Sunday 2 Saturday 1 Monday is on list. Monday is NOT on list. Start of list: End of list. 12 Programming With Java ICS201 Traversing a Linked List o If a linked list already contains nodes, it can be traversed as follows: 1. Set a local variable equal to the value stored by the head node (its reference). 2. This will provides the location of the first node 3. After accessing the first node, the accessor method for the link instance variable will provide the location of the next node. 4. Repeat this until the location of the next node is equal to null. 13 Programming With Java ICS201 Traversing a Linked List This reference is position.link When position is at this last node, position.link = null 14 Programming With Java ICS201 Adding a node to a Linked List o The method add adds a node to the start of the linked list. This makes the new node become the first node on the list. o The variable head gives the location of the current first node of the list. Therefore, when the new node is created, its link field is set equal to head. Then head is set equal to the new node. 15 Programming With Java ICS201 Adding a node at the Start 16 Programming With Java ICS201 Node Inner Classes o The linked list class discussed so far is dependent on an external node class. o A linked list or similar data structure can be made selfcontained by making the node class an inner class. o A node inner class so defined should be made private, unless used elsewhere. This can simplify the definition of the node class by eliminating the need for accessor and mutator methods. Since the instance variables are private, they can be accessed directly from methods of the outer class without causing a privacy leak. 17 Example (Linked List Class) Programming With Java ICS201 public class LinkedList{ private class Node { private String item ; private int count ; private Node link ; public Node ( ) { link = null ; item = null ; count = 0 ; } public Node ( String newitem , int newCount , Node linkValue) { item = newitem ; count = newCount ; link = linkValue; } } private Node head; public LinkedList( ) { head = null; } continued 18 Programming With Java ICS201 Example (Linked List Class) /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ public void addToStart(String itemName, int itemCount) { head = new Node(itemName, itemCount, head); } /** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.link ; return true; } else return false; } /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; The outer class has direct access to Node position = head; the inner class’s instance variables, such as link. while (position != null) { count++; position = position.link; } return count; } continued 19 Programming With Java ICS201 Example (Linked List Class) public boolean contains(String item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node find(String target) { Node position = head; String itemAtPosition; while (position != null) { itemAtPosition = position.item; if (itemAtPosition.equals(target)) return position; position = position.link; } return null; //target was not found } public void outputList( ) { Node position = head; while (position != null) { System.out.println(position.item + " “ + position.count); position = position.link; } } public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; }} 20 Programming With Java ICS201 Example (Linked List Class) class LinkedListDemo { public static void main(String[] args) { LinkedList list = new LinkedList( ); list.addToStart("Saturday", 1); list.addToStart("Sunday", 2); list.addToStart("Monday", 3); System.out.println("List has " + list.size( ) + " nodes."); list.outputList( ); if (list.contains("Monday")) System.out.println("Monday is on list."); else System.out.println("Monday is NOT on list."); list.deleteHeadNode( ); if (list.contains("Monday")) System.out.println("Monday is on list."); else System.out.println("Monday is NOT on list."); Output: List has 3 nodes. Monday 3 Sunday 2 Saturday 1 Monday is on list. Monday is NOT on list. Start of list: End of list. list.clear() ; } } System.out.println("Start of list:"); list.outputList( ); System.out.println("End of list."); 21 Programming With Java ICS201 A Generic Linked List o A linked list can be created whose Node class has a type parameter T for the type of data stored in the node. Therefore, it can hold objects of any class type, including types that contain multiple instance variable. The type of the actual object is plugged in for the type parameter T. o For the most part, this class can have the same methods, coded in basically the same way, as the previous linked list example. The only difference is that a type parameter is used instead of an actual type for the data in the node. o Other useful methods can be added as well. 22 Example (Generic Linked List Class) Programming With Java ICS201 public class LinkedList<T>{ private class Node<T> { private T data ; private Node<T> link ; public Node ( ) { link = null ; data= null ; //count = 0 ; } public Node ( T newdata , Node<T> linkValue) { data= newdata ; link = linkValue; } } private Node<T> head; public LinkedList( ) { head = null; } continued 23 Programming With Java ICS201 Example (Generic Linked List Class) /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ public void addToStart(T itemData) { head = new Node<T>(itemData, head); } /** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.link ; return true; } else return false; } /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; Node<T> position = head; while (position != null) { count++; position = position.link; } return count; } continued 24 Programming With Java ICS201 Example (Generic Linked List Class) public boolean contains(T item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node find(T target) { Node<T> position = head; TitemAtPosition; while (position != null) { itemAtPosition = position.data; if (itemAtPosition.equals(target)) return position; position = position.link; } return null; //target was not found } public void outputList( ) { Node<T> position = head; while (position != null) { System.out.println(position.data); position = position.link; } } public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; }} 25 Example (Generic Linked List Class) Programming With Java ICS201 /** A Sample Class for the Data in a generic Linked List*/ public class Entry { private String item ; private int count ; public Entry (String itemData , int countData ) { item = itemData ; count = countData ; } } class GenericLinkedListDemo { public static void main(String[] args) { LinkedList<Entry> list = new LinkedList<Entry>( ); Entry entry1 = new Entry("Saturday", 1) ; list.addToStart(entry1); Entry entry2 = new Entry(“Sunday", 2) ; list.addToStart(entry2); Entry entry3 = new Entry(“Monday", 3) ; list.addToStart(entry3); System.out.println("List has " + list.size( ) + " nodes."); list.outputList( ); } 26 Programming With Java ICS201 Iterators o A collection of objects, such as the nodes of a linked list, must often be traversed in order to perform some action on each object An iterator is any object that enables a list to be traversed in this way. o A linked list class may be created that has an iterator inner class. If iterator variables are to be used outside the linked list class, then the iterator class would be made public. The linked list class would have an iterator method that returns an iterator for its calling object. Given a linked list named list, this can be done as follows: LinkedList.ListIterator i = list.iterator(); 27 Programming With Java ICS201 Iterators o The basic methods used by an iterator are as follows: restart: Resets the iterator to the beginning of the list. hasNext: Determines if there is another data item on the list. next: Produces the next data item on the list. 28 Programming With Java ICS201 Iterators (Deleting a Node) o An iterator is normally used to add or delete a node in a linked list. o Given iterator variables position and previous, the following two lines of code will delete the node at location position: previous.link = position.link; position = position.link; Note: previous points to the node before position. o The iterator variables position and previous can be used to add a node as well: previous will point to the node before the insertion point, and position will point to the node after the insertion point Node temp = new Node(newData,position); previous.link = temp; 29 Programming With Java ICS201 Example (Iterators) public class LinkedListIter { private class Node { private String item; private Node link; public Node( ) { item = null; link = null; } public Node(String newItem, Node linkValue) { item = newItem; link = linkValue; } } //End of Node inner class public class ListIterator // An inner class for LinkedListIter { private Node position; private Node previous; // Previous value of position public ListIterator() { position = head; // Instance variable head of outer class previous = null; } 30 Programming With Java ICS201 Example (Iterators) public void restart( ) { position = head; // Instance variable head of outer class previous = null; } public String next( ) { if (!hasNext( )) return “ "; String toReturn = position.item; previous = position; position = position.link; return toReturn; } public boolean hasNext() { return (position != null); } /** Returns the next value to be returned by next() **/ public String peek( ) { if (!hasNext( )) return “ "; return position.item; } 31 Programming With Java ICS201 Example (Iterators) /** Adds a node before the node at location position. previous is placed at the new node. If hasNext() is false, then the node is added to the end of the list. If the list is empty, inserts node as the only node.**/ public void addHere(String newData) { if (position == null && previous != null) { // at end of list previous.link = new Node(newData, null); } else if (position == null || previous == null) // at head of list LinkedListIter.this.addToStart(newData); else { // Between nodes Node temp = new Node(newData, position); previous.link = temp; previous = temp; } } 32 Programming With Java ICS201 Example (Iterators) /** Deletes the node at location position and moves position to the next "node"**/ public void delete( ) { if (previous == null) { head = head.link; position = head; } else { previous.link = position.link; position = position.link; } } } // End of ListIterator inner class private Node head; public ListIterator iterator() { return new ListIterator(); } <The other methods and constructors are identical to those in program page18-21> 33 Programming With Java ICS201 Example (Iterators) public static void main(String[ ] args) { LinkedListIter list = new LinkedListIter(); LinkedListIter.ListIterator i = list.iterator(); list.addToStart("shoes"); list.addToStart("orange juice"); list.addToStart("coat"); System.out.println("List contains"); i.restart(); while (i.hasNext()) System.out.println(i.next()); System.out.println(); i.restart(); i.next(); i.delete(); System.out.println("List now contains"); i.restart(); while (i.hasNext()) System.out.println(i.next()); System.out.println(); i.restart(); i.next(); i.addHere("socks"); i.restart(); System.out.println("List now contains"); while (i.hasNext()) System.out.println(i.next( )); System.out.println(); } } Output: List contains coat orange juice shoes List now contains coat shoes List now contains coat socks shoes 34