Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14 Introduction to Data Structures. Topics Linked Lists Concepts and Structure Linked Lists of Objects Implementing a Stack Using a Linked List.

Similar presentations


Presentation on theme: "Chapter 14 Introduction to Data Structures. Topics Linked Lists Concepts and Structure Linked Lists of Objects Implementing a Stack Using a Linked List."— Presentation transcript:

1 Chapter 14 Introduction to Data Structures

2 Topics Linked Lists Concepts and Structure Linked Lists of Objects Implementing a Stack Using a Linked List Implementing a Queue Using a Linked List Implementing a Stack Using an Array Implementing a Queue Using an Array Sorted Linked Lists Doubly Linked Lists Linked Lists of Generic Types Recursively Defined Linked Lists

3 Linked Lists In Chapters 8 and 9, we introduced the concepts of arrays and the ArrayList class. Arrays and ArrayLists are examples of data structures, which are methodologies a program uses to store data in memory. In some situations, the number of data items may dynamically increase or decrease as the program executes. A Linked List is a data structure that shrinks and grows one object at a time, keeping the size of the list to a minimum at all times.

4 Linked Lists A linked list can be thought of as a chain of linked nodes. A node is an object with two attributes: –data –the location of the next node in the chain

5 Linked Lists The data stored at each node can be primitive data types (int, char, double..) or objects (Book, Astronaut, Player…) Here is an example of a list of Player objects with three instance variables: ID, name, and game.

6 A Linked List of Primitive Types First we code a linked list where the data in the nodes are ints. We define the node class, IntegerNode, which has two instance variables: –data, an int –an IntegerNode reference, next, which is a link to the next node in the list. See Example 14.1 IntegerNode.java

7 A LinkedList Class Next we define an IntegerLinkedList class, which will implement the linked list of IntegerNode objects. It has two instance variables: an IntegerNode reference, named head, representing the first node in the list an int, named numberOfItems, representing the number of nodes in the list. We will provide an accessor for numberOfItems, but no mutator because clients should not change this value.

8 Do not provide an accessor or mutator method for the head node instance variable of the linked list. This will protect the head node from being accessed or changed outside the class. Similarly, do not include a mutator method for the number of items in the list. Only the insert and delete methods of the linked list class should alter the number of items. SOFTWARE ENGINEERING TIP

9 Including an instance variable in the linked list class that stores the number of items in the list allows for quick access to the size of the list, as needed. SOFTWARE ENGINEERING TIP

10 Basic Functionality of a Linked List Clients should be able to insert and delete items, and display all the items in a list. We implement the following APIs: Return valueMethods of the LinkedList Class voidinsert( int value ) inserts value at the beginning of the list. booleandelete( int value ) removes the first item in the list that is equal to value and returns true. If there is no such item in the list, the method returns false. StringtoString( ) returns a String representation of the list

11 The toString Method The toString method traverses the list (visits every node) and returns a String containing the data for all the objects in the list. public String toString( ) { String listString = ""; IntegerNode current = head; for( int i = 0; i < numberOfItems; i++ ) { listString += current.getData( ) + " "; current = current.getNext( ); } return listString; }

12 Provide a toString method that traverses the list. This is helpful at the debugging stage when testing other methods, in particular insert and delete. SOFTWARE ENGINEERING TIP

13 The insert Method The insert method performs the following steps: 1. Instantiate a new node containing the int to be inserted. 2. Attach that node at the beginning of the list, that is, make that node point to the previous head node. If the list originally was empty and the previous head node has the value null, then the next field of the new node is given the value null. 3. Indicate that the new node is now the head of the list, that is, make head point to the new node. 4. Increase the number of items in the list by 1.

14 The insert Method The original list: The new node is instantiated: The new node is attached to the beginning of the list: head now points to the new node:

15 The delete Method To find the node to delete, we traverse the list. Traversing a list means to loop through the list, visiting each node in order. Three outcomes are possible: 1.The item is found and is not the head of the list. 2.The item is found and is the head of the list. 3.The item is not found, and therefore, cannot be deleted. As we traverse the list, we maintain a reference to the previous node, because we will need to connect that node to the node following the deleted node.

16 Deleting an Item That is Not the Head The list before deleting the item with the value 8: The previous node is connected to the node after current:

17 Deleting an Item That is the Head The list before deleting the item whose value is 7: The link from the first node becomes the new head: See Example 14.2 IntegerLinkedList.java

18 When traversing a list and calling a method with a node reference, be sure that the node reference is not null. Calling a method with a null node reference will generate a NullPointerException at run time. Because compound expressions are evaluated left to right, if a compound logical expression uses an object reference to call a method, check whether the object reference is null in the first expression. Common Error Trap

19 Testing a Linked List Class Be sure to test all possibilities. Insert: –inserting into an empty list –inserting into a nonempty list Delete: –attempting to delete from an empty list –deleting the first item in the list –deleting the last item in the list –deleting an item in the middle of the list. –attempting to delete an item not in the list See Example 14.3 IntegerLinkedListTest.java

20 Linked Lists of Objects To implement a linked list of Player objects, we will code three classes: –A Player class, encapsulating a player. –A PlayerNode, encapsulating a node. –A List class, encapsulating a linked list of Players.

21 Linked Lists of Objects Next we will define a linked list where the items in the lists are objects, specifically, Player objects. The Player class encapsulates game players and has three instance variables: –id, an int –name, a String (the player’s name) –game, a String (the player’s favorite game) See Example 14.4 Player.java

22 The PlayerNode Class For this list, the items of the nodes will contain Player objects. The PlayerNode class has two instance variables: –player, a Player object reference –next, a PlayerNode object reference (the next node in the list) See Example 14.5 PlayerNode.java

23 A Linked List Shell Class Because we anticipate having many linked list classes, we set up a linked-list superclass from which our more specialized linked-list classes (unsorted, sorted, stacks, queues,...) will inherit. This class will provide basic utility methods that test whether the list is empty and return the number of items in the list, and also a toString method that traverses the list. This class will be abstract.

24 The ShellLinkedList Class The ShellLinkedList class has two instance variables: –head, a PlayerNode object reference (the first node in the list) –numberOfItems, an int (the number of items in the list, for convenience) We declare the instance variables as protected so that our subclasses will inherit them. See Example 14.6 ShellLinkedList.java

25 ShellLinkedList Methods Return valueMethod name and argument list intgetNumberOfItems( ) returns the number of items in the list booleanisEmpty( ) returns true if the list is empty, false otherwise StringtoString( ) returns a String representation of the list

26 Another Way to Code toString Instead of using a for loop with the number of nodes, we can use a while loop and check for the end of the list. public String toString( ) { String listString = ""; PlayerNode current = head; while( current != null ) //check for last node { listString += current.getPlayer( ).toString( ) + “\n"; current = current.getNext( ); } return listString; }

27 Linked List Functionality Our ShellLinkedList provides this functionality: –insert an item at the beginning of the list –delete an item based on the value of an instance variable. For the Player class, we chose ID, but we could also write delete methods based on other instance variables. We will return the Player object deleted. –retrieve, or peek at, the contents of a node. This method returns the object identified by ID, but does not delete it.

28 The DataStructureException Class We want our delete method and peek method to return a reference to the item. But there will be instances where we cannot find an item (empty list, item not found), and we do not want to return null. In these cases, we will throw an exception. Thus, we create our own exception class. The constructor takes an error message identifying the cause of the error. See Example 14.7 DataStructureException.java

29 PlayerLinkedList Methods Return valueMethod name and argument list voidinsert( Player p ) inserts Player p at the beginning of the list Playerdelete( int searchID ) returns and removes the first Player of the list whose ID is equal to searchID. If there is no such Player in the list, it throws a DataStructureException Playerpeek( int searchID ) returns the first Player of the list whose ID is equal to searchID. If there is no such Player in the list, it throws a DataStructureException

30 A Stack Using a Linked List A stack is a linear data structure that organizes items in a last in, first out (LIFO) manner. For example, cafeteria trays are typically organized in a stack. The tray at the top of the stack was put on the stack last, and will be taken off the stack first. Standard operations for a stack are: –push - place an item on the stack –pop - remove the last item placed on the stack

31 A Linked List Class Implementing a Stack In a stack implemented as a linked list: –To push, we insert at the beginning of the linked list. –To pop, we delete the first item in the linked list. Thus, deletion is not based on value; we always delete the first item in the list. –To peek, we return the first object on the list without deleting it. –Both pop and peek throw a DataStructureException if unsuccessful.

32 PlayerStackLinkedList Methods See Example 14.10 PlayerStackLinkedList.java Return valueMethod name and argument list voidpush( Player p ) inserts Player p at the top of the stack Playerpop( ) returns and removes the first Player of the list. If the list is empty, the method throws a DataStructureException. Playerpeek( ) returns the first Player on the list without deleting it. If the list is empty, the method throws a DataStructureException.

33 A Queue Using a Linked List A queue is a linear data structure that organizes items in a first in, first out (FIFO) manner. For example, people waiting at the bank teller are typically organized in a queue. The person at the front of the queue arrived first, and will be served, or taken off the queue, first. Standard operations for a queue are: –enqueue - place an item at the end of the queue –dequeue - remove the item at the beginning of the queue

34 A Linked List Class Implementing a Queue In a queue implemented as a linked list, we enqueue by inserting at the end of the linked list. In a queue implemented as a linked list, we dequeue by deleting the first item in the linked list. Again, deletion is not based on value; it is based on position.

35 A Linked List Class Implementing a Queue Because a queue inserts items at the end of the list, we will add an instance variable, tail, (a PlayerNode reference), representing the last node in the list. In this way, we do not have to traverse the list every time we insert an item. We will need to update that reference every time an item is inserted. See Example 14.11 PlayerQueueLinkedList.java

36 PlayerQueueLinkedList Methods Return valueMethod name and argument list voidenqueue( Player p ) inserts Player p at the end of the list Playerdequeue( ) returns and removes the first Player of the list. If the list is empty, the method throws a DataStructureException Playerpeek( ) returns the first Player on the list without deleting it. If the list is empty, the method throws a DataStructureException

37 Inserting in a (non-empty) Linked List Representing a Queue The node to insert is instantiated. The new node is attached to the end of the queue. tail is updated.

38 A Linked List Class Implementing a Queue A queue has a front and a back, represented by head and tail, respectively. Could they be inverted, i.e. could head represent the back of the queue and tail represent the front of the queue? –This would be highly inefficient because when we delete, we would need to traverse the list in order to update tail. Indeed, we cannot go backward in the list from tail in order to access the next-to-last node (which becomes tail after the deletion).

39 Array Representation of Stacks If we know in advance the maximum number of objects on the stack, we can represent the stack using an array. This is easier to implement than a linked list. –We add items to the stack starting at index 0. –We maintain an index top, short for top of the stack. –The last element inserted is at index top.

40 An Array Representing a Stack There are three items on the stack: indexPlayer object top2 ( 8, Gino, Diablo ) 1 ( 7, Sarah, Mario ) 0 ( 2, Jin, Golf )

41 Our Stack after Inserting Player ( 6, Steve, NFL ) Now there are four items on the stack: indexPlayer object top3 ( 6, Steve, NFL ) 2 ( 8, Gino, Diablo ) 1 ( 7, Sarah, Mario ) 0 ( 2, Jin, Golf )

42 Our Stack After Popping Once Now there are three items on the stack. Player ( 6, Steve, NFL ) is not on the stack. indexPlayer object 3 ( 6, Steve, NFL ) top2 (8, Gino, Diablo ) 1 ( 7, Sarah, Mario ) 0 ( 2, Jin, Golf )

43 Instance Variables for our Stack We will have three instance variables: –A constant STACK_SIZE, representing the capacity of the stack. –An array stack, storing the elements of the stack. –An int top, representing the top of the stack. public class ArrayStack { private static final int STACK_SIZE = 100; private Player [] stack; private int top; …. }

44 Constructor for our Stack The constructor performs two functions: –It instantiates the array, stack. –It initializes top to -1 to reflect that the stack is empty. If top were initialized to 0, that would mean that an element is on the stack, at index 0. public ArrayStack( ) { stack = new Player[STACK_SIZE]; top = -1; // stack is empty }

45 Utility Methods for our Stack We will have three utility methods: –isEmpty, returning true if the stack is empty. –isFull, returning true if the stack is full. –toString, returning a String representation of the stack. public boolean isEmpty( ) { return ( top == -1 ); } public boolean isFull( ) { return ( top == ( STACK_SIZE – 1 ) ); }

46 toString Method for our Stack public String toString( ) { String stackString = ""; for ( int i = top; i >= 0; i-- ) stackString += ( i + ": " + stack[i] + "\n" ); return stackString; }

47 push Method for our Stack public boolean push( Player p ) { if ( ! isFull( ) ) { stack[++top] = p; return true; } else return false; }

48 pop Method for our Stack public Player pop( ) throws DataStructureException { if ( ! isEmpty( ) ) return ( stack[top--] ); else throw new DataStructureException ( "Stack empty: cannot pop" ); } See Example 14.12 ArrayStack.java

49 Do not confuse the top of the stack with the last element in the array. Array elements with array indexes higher than top are not on the stack. Common Error Trap

50 Array Representation of Queues We can also represent a queue using an array. The first (inefficient) idea is to represent the queue with a standard array; two indexes, front and back, represent the front and back of the queue. –To enqueue, we could increment back by 1 and store the player at array index back. –To dequeue, we could return the element at index front and increment front by 1. The problem with this approach is that the number of available elements in the array will shrink over time.

51 Queue after Inserting First 5 Elements Player( 5, Ajay, Sonic ) was enqueued first. indexPlayer object 7 6 5 back4 ( 6, Steve, NFL ) 3 ( 8, Gino, Diablo ) 2 ( 7, Sarah, Mario ) 1 ( 2, Jin, Golf ) front0 ( 5, Ajay, Sonic )

52 Queue after Dequeueing Once Element at index 0 is no longer usable. indexPlayer object 7 6 5 back4 ( 6, Steve, NFL ) 3 (8, Gino, Diablo ) 2 ( 7, Sarah, Mario ) front1 ( 2, Jin, Golf ) 0 ( 5, Ajay, Sonic )

53 Using a Circular Array The solution is to consider the array as a circular array. –After back reaches the last array index, we start enqueueing again at index 0. –If the array has size 8, the index "after" 7 is 0. The useful capacity of the array never shrinks. If the array has size 8, the useful capacity of the array is always 8.

54 An Empty Queue

55 Enqueueing One Element

56 Enqueueing a Second Element

57 Enqueueing a Third Element

58 Enqueueing a Fourth Element

59 Dequeueing Once

60 Dequeueing Again

61 Full Queue In a queue implemented as a circular array, how do we know when the queue is full? When the queue is full, we have the following relationship between front and back: ( back + 1 – front ) % QUEUE_SIZE == 0

62 A Full Queue

63 Empty Queue When the queue is empty, we also have the same relationship between front and back! ( back + 1 – front ) % QUEUE_SIZE == 0

64 An Empty Queue

65 Queue Full or Empty? So when ( back + 1 – front ) % QUEUE_SIZE == 0 is the queue full or empty? We cannot tell. There is an easy way to solve this problem: Keep track of the number of items in the queue.

66 Instance Variables for our Queue We will have five instance variables: –A constant representing the capacity of the queue. –An array, storing the elements of the queue. –An int, front, representing the front of the queue. –An int, back, representing the back of the queue. –An int, numberOfItems, storing the number of items in the queue. public class ArrayQueue { private static final int QUEUE_SIZE = 8; private Player [] queue; private int front; private int back; private int numberOfItems; … }

67 Constructor for our Queue The constructor performs four functions: –instantiates the array, queue. –initializes front to 0 –initializes back to QUEUE_SIZE – 1 –initializes numberOfItems to 0 to reflect that the queue is empty. public ArrayQueue( ) { queue = new Player[QUEUE_SIZE]; front = 0; back = QUEUE_SIZE - 1; numberOfItems = 0; }

68 Utility Methods for our Queue We will have three utility methods: –isEmpty, returning true if the the queue is empty. –isFull, returning true if the the queue is full. –toString, returning a String representation of the queue. public boolean isEmpty( ) { return ( numberOfItems == 0 ); } public boolean isFull( ) { return ( numberOfItems == QUEUE_SIZE ); }

69 The toString Method public String toString( ) { String queueString = ""; for ( int i = front; i < front + numberOfItems; i++) queueString += queue[i % QUEUE_SIZE].toString( ) + "\n"; return queueString; }

70 dequeue Method for our Queue public Player dequeue( ) throws DataStructureException { if ( !isEmpty( ) ) { front = ( front + 1 ) % QUEUE_SIZE; numberOfItems--; return queue[( QUEUE_SIZE + front – 1 ) % QUEUE_SIZE]; } else throw new DataStructureException ( "Queue empty: cannot dequeue" ); }

71 enqueue Method for our Queue public boolean enqueue( Player p ) { if ( !isFull( ) ) { queue[( back + 1 )% QUEUE_SIZE] = p; back = ( back + 1 ) % QUEUE_SIZE; numberOfItems++; return true; } else return false; } See Example 14.14 ArrayQueue.java

72 Do not confuse array index 0 and QUEUE_SIZE - 1 with front and back. In a queue represented by a circular array, the indexes 0 and QUEUE_SIZE - 1 are irrelevant. Common Error Trap

73 Implementing a Stack or a Queue as an Array vs as a Linked List ArrayLinked List Easily expandableNoYes Direct access to every itemYesNo Easy to codeYesNo

74 Sorted Linked List For some applications, it may be desirable for a Linked List to be sorted. The items can be sorted based on the value of one of their instance variables, called a key. A Linked List that stores its items in ascending (or descending) order according to a key value is called a Sorted Linked List. –For example, for a Sorted Linked List of Player objects, we could arrange the list by the key id. Without loss of generality, we will consider a list sorted in ascending order.

75 PlayerSortedLinkedList Methods Return valueMethod name and argument list voidinsert( Player p ) inserts Player p in the location that keeps the list sorted Playerdelete( int searchID ) returns and removes the first Player of the list whose ID is equal to searchID. If there is no such Player on the list, the method throws a DataStructureException. Playerpeek( int searchID ) returns the first Player of the list whose ID is equal to searchID. If there is no such Player on the list, the method throws a DataStructureException.

76 Inserting in a Sorted Linked List When inserting an item in a sorted linked list, we must keep the list sorted; that is, after insertion is performed, the list is still sorted. –If the key value of the item to be inserted is smaller than all the key values in the list, then we insert the item at the beginning of the list. This operation is identical to our previous insertion in a linked list. –Otherwise, we will insert the item somewhere in the middle or at the end of the list.

77 Inserting in the Middle or at the End of a Sorted Linked List 1.Instantiate the new node. 2.Traverse the list to identify the location to insert the new node. Call the node before the insertion point previous, and the node after current. 3.Attach the new node to current. 4.Attach previous to the new node. 5.Increment the number of items.

78 Inserting in the Middle or End of a Sorted List Instantiate new node and find appropriate location Attach new node to current Attach previous to new node

79 Deleting from a Sorted Linked List Our delete method is similar to the previous delete method of a linked list. If the key value we are trying to delete is not in the list, we can determine that fact as soon as we visit an item with a value greater than the search value. At that point, we can exit the method. See Example 14.15 PlayerSortedLinkedList.java

80 Testing a Sorted Linked List Class When testing the insert method of a sorted linked list class, be sure to test all possibilities: –inserting into an empty list. –inserting at the beginning of the list. –inserting in the middle or at the end of the list. Traverse the list after each insert to verify that the item was inserted at the correct location. See Example 14.16 PlayerSortedLinkedListTest.java

81 Doubly Linked List Each node has two links: one forward (as before) and one backward. The PlayerNode class now has an additional instance variable: –previous, the previous PlayerNode. Thus, we can traverse a doubly linked list either forward or backwards. Every time we insert or delete, both links must be updated.

82 Doubly Linked Node A doubly linked node looks like this –The right arrow represents next. –The left arrow represents previous.

83 Inserting in a Doubly Linked List There are three cases: –insert at the beginning. –insert in the middle. –insert at the end. Updating the links will differ in the three cases above. Furthermore, when a node is inserted at the beginning, head needs to be updated.

84 Inserting in the Middle In order to insert a node before a node named current, the following steps need to be performed: –Instantiate a new node. –Set two forward links: new node to current, node before current to new node. –Set two backward links: current to new node, new node to node before current. –Update the number of items. Updating the links will differ in the three cases above.

85 Inserting into a Doubly Linked List 1. Instantiate the new node 2. Set next in new node to current.

86 Inserting into a Doubly Linked List 3. Set next in node before current to the new node. 4. Set previous in the new node to the node before current.

87 Inserting into a Doubly Linked List 5. Set previous in current to the new node.

88 Inserting into a Doubly Linked List Here is the code to perform the insertion: PlayerNode pn = new PlayerNode( p ); // 1 pn.setNext( current ); // 2 ( current.getPrevious( ) ).setNext( pn ); // 3 pn.setPrevious( current.getPrevious( ) ); // 4 current.setPrevious( pn ); // 5 numberOfItems++; // 6 Note that the order of execution is important to preserve the links.

89 Deleting from a Doubly Linked List There are four cases: –delete at the beginning. –delete in the middle. –delete at the end. –cannot delete. Updating the links will differ in the first three cases above. Furthermore, when a node is deleted at the beginning, head needs to be updated.

90 Deleting in the Middle of a Doubly Linked List We will delete the Player with id 7 1.Set next in the node before current to the node after current. 2. Set previous in the node after current to the node before current.

91 Deleting in the Middle of a Doubly Linked List Here is the code: ( current.getPrevious( ) ).setNext( current.getNext( ) ); // Step 1 ( current.getNext( ) ).setPrevious( current.getPrevious( ) ); // Step 2 numberOfItems--; // Step 3

92 Linked Lists of Generic Types To write a linked list that accepts items of any class, we can use generic types. In a linked list, the data of the item is stored in the node; thus, the data in our Node class will be a generic object.

93 Generic Class Syntax The basic syntax for the header of a class that implements generics is: AccessModifier class className For the identifier for our generic class, we will use the upper case letter T. Thus, for our Node class, the header will be: public class Node Inside the class, we can then use that identifier, here T, as we would use an existing or user-defined class. For example, to declare an instance variable named data of class T, we write: private T data;

94 Generic Object References In order to use an object reference of a class implementing generics, we use the following syntax: ClassName Thus, in order to declare an object reference of the Node class as a return type or a parameter for a method, we use the notation Node See Example 14.19 Node.java and Example 14.20 ShellLinkedList.java

95 Generic Linked List Code We implemented our delete method differently. We cannot delete an item based on the value of one of its fields because we do not know what the fields of that item are, since that item is a generic object. Thus, the parameter of our delete method is a generic object of the same type as the items in the list. There is no need to return an item if we find it and can delete it because we already have that item as the parameter of the method. So, the delete method returns a boolean value: true if we were able to delete the item, false otherwise. In order to compare item with the items in the list, we call the equals method, inherited by any class from the Object class, and which will need to be overwritten in the class the client specifies as the type for the linked list. See Example 14.21 GenericLinkedList.java And Example 14.22 LinkedListTest.java

96 Recursively Defined Linked Lists A recursively defined linked list is made up of two items: –An item, the first item in the list. –A linked list, the rest of the linked list. Thus, we have two instance variables: –first, the first item in the list. –rest, a linked list itself, the rest of the list. first (an item) rest (a linked list)

97 PlayerRecursiveLinkedList Methods Return valueMethod name and argument list voidinsert( T item ) inserts Player p at the beginning of the list booleandelete( T item ) removes the first object of the list that matches item and returns true. If there is no such item on the list, the method returns false.

98 Inserting in a Recursively Defined Linked List Unless the list is a sorted list, we will insert at the beginning of the list. After insertion: –first will hold the item just inserted –rest will hold the original list

99 Inserting in a Recursively Defined Linked List The original list, before inserting Player p: The list after inserting Player p: p1 r1 p ned list) first rest firstrest p1 r1

100 Deleting from a Recursively Defined Linked List Our recursive delete method deletes the first item on the list whose key value matches a given key value. There are three base cases: –Empty list –The item to delete is the first one on the list –The item to delete is not the first one on the list and the rest of the list is empty In the general case, we make a recursive call to try to delete from the rest of the list. See Example 14.23 RecursiveLinkedList.java

101 Deleting the First Item in a Recursively Defined Linked List The original list, before deleting Player p: p ned list) firstrest p1 r1

102 Deleting the First Item in a Recursively Defined Linked List first is assigned the first item of the rest of the list: first = rest.first; p1 ned list) firstrest p1 r1

103 Deleting the First Item in a Recursively Defined Linked List rest is assigned the rest of the rest of the list: rest = rest.rest; p1 r1 firstrest

104 Processing a Recursively Defined Linked List Generally, we want to do the following: –If the list is empty, the method returns. –If the list is not empty, process first, the first element of the list. The method may or may not return at this point. If rest is null, the method returns. If rest is not null, make a recursive call on rest.

105 Coding the toString Method of a Recursively Defined Linked List public String toString( ) { String listString = "": if ( first != null ) { listString = first.toString( ) + "\n"; if ( rest != null ) listString += rest.toString( ); } return listString; }

106 When processing a recursively defined list, not testing for all the base case conditions can result in a NullPointerException at run time. Common Error Trap

107 When implementing methods of a recursively defined class, think in terms of implementing recursive methods. SOFTWARE ENGINEERING TIP


Download ppt "Chapter 14 Introduction to Data Structures. Topics Linked Lists Concepts and Structure Linked Lists of Objects Implementing a Stack Using a Linked List."

Similar presentations


Ads by Google