Introduction to - PowerPoint PPT Presentation

1 / 119
About This Presentation
Title:

Introduction to

Description:

Diablo. 5. Ajay. Sonic. head. null. 7. Sarah. Mario. Linked Lists ... Diablo. 5. Ajay. Sonic. head. null. 7. Sarah. Mario. Inserting at the Beginning of a List ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 120
Provided by: JulieAn9
Category:

less

Transcript and Presenter's Notes

Title: Introduction to


1
Chapter 14
  • Introduction to
  • Data Structures
  • (From the book slides)

2
Topics
  • Linked Lists
  • A Stack Using a Linked List
  • A Queue Using a Linked List
  • A Stack Using an Array
  • A Queue Using an Array
  • Sorted Linked Lists
  • Doubly Linked Lists
  • 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
5
Linked Lists
  • The data stored at each node can be primitive
    data types (int, char, ..) or objects (Book,
    Astronaut, )
  • Here is an example of a list of Player objects.

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
6
Linked Lists
  • To implement a linked list of Players, 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.

7
The Player Class
  • The Player class has three instance variables
  • id, an int
  • name, a String
  • game, a String
  • See Example 14.1 Player.java

8
The PlayerNode Class
  • 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.2 PlayerNode.java

9
The ShellLinkedList Class
  • The ShellLinkedList class is abstract and 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 declared this class abstract because we
    anticipate having many linked list classes
    (unsorted, sorted, stacks, queues, ...)
  • We declare the instance variables as protected so
    that our subclasses will inherit them.
  • See Example 14.3 ShellLinkedList.java

10
ShellLinkedList Methods
11
The toString Method of the ShellLinkedList Class
  • 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 ""
  • PlayerNode current head
  • for( int i 0 i lt numberOfItems i )
  • listString
  • current.getPlayer( ).toString( ) "\n"
  • current current.getNext( )
  • return listString

12
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 (current null)
  • 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

13
The DataStructureException Class
  • We are almost ready to code some meaningful
    methods of our linked list class, such as insert
    and delete.
  • We want our delete method to return the item just
    deleted.
  • But there will be instances where we cannot
    delete 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.
  • See Example 14.4 DataStructureException.java

14
Linked List Functionality
  • At the minimum, we want to
  • insert an item
  • delete an item
  • retrieve, or peek at, the contents of a node

15
Linked List Functionality
  • There are many options for inserting an item in
    the list at the beginning, at the end, at a
    certain position, before or after a certain item.
    We will implement insertion at the beginning of
    the list.
  • There are also many options for deleting an item
    from the list at the beginning, at the end, at a
    certain position, based on a certain criteria. We
    will implement deletion based on the value of an
    instance variable we have chosen id.

16
PlayerLinkedList Methods
17
Inserting at the Beginning of a List
  • Instantiate the new node.
  • Attach the node to the beginning of the list.
  • Update head.
  • Update the number of items.

18
Inserting at the Beginning of a List
  • Our original Linked List

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
19
Inserting at the Beginning of a List
  • Step 1 Instantiate a new node
  • PlayerNode pn new PlayerNode( p )
  • // here, p is Player( 6, Steve, NFL )

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
6 Steve NFL
null
20
Inserting at the Beginning of a List
  • Step 2 Attach the new node to the beginning of
    the list
  • pn.setNext( head )

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
6 Steve NFL
null
head
21
Inserting at the Beginning of a List
  • Step 3 Update head
  • head pn

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
6 Steve NFL
null
head
22
Deleting from a Linked List
  • Locate the node to delete.
  • There are two cases
  • The node is in the middle or at the end of the
    list.
  • The node is the head node.
  • In the second case, we need to update head.
  • Update the number of items (if successful).
  • See Example 14.5 PlayerLinkedList.java

23
Deleting in the Middle or the End of a List
  • Before deleting the Player whose id is 8

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
previous
current
24
Deleting in the Middle/End of a List
  • Connect previous to the node after current
  • previous.setNext( current.getNext( ) )
  • current is now unreachable, and is deleted.

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
previous
current
25
Deleting at the Beginning of a List
  • Before deleting the Player whose id is 7

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
current
26
Deleting at the Beginning of a List
  • Update head
  • head head.getNext( )
  • current is now unreachable, and is deleted.

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
current
27
Common ErrorTraps
  • 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
    runtime.
  • 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.

28
Software Engineering Tips
  • 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.

29
More Software Engineering Tips
  • Provide a toString method that traverses the
    list. This is helpful at the debugging stage when
    testing other methods, in particular insert and
    delete.
  • Do not return an object reference to an item
    still in the list. Instead, return a reference to
    a copy of that item.

30
Testing a Linked List Class
  • When 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
  • attempting to delete an item not in the list
  • deleting the first item in the list
  • deleting the last item in the list
  • deleting an item in the middle of the list.
  • See Example 14.6 PlayerLinkedListTest.java

31
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

32
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.
  • See Example 14.7 PlayerStackLinkedList.java

33
PlayerStackLinkedList Methods
34
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

35
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 stack 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.

36
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.8 PlayerQueueLinkedList.java

37
A Linked List Implementing a Queue
  • Here is an example of a queue of Player objects
    represented by a linked list.

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
tail
38
PlayerQueueLinkedList Methods
39
Inserting in a (non-empty) Linked List
Representing a Queue
  • Our original list

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
tail
40
Inserting in a (non-empty) Linked List
Representing a Queue
  • Step 1 Instantiate a new node
  • PlayerNode pn new PlayerNode( p )
  • // here, p is Player( 6, Steve, NFL )

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
null
head
tail
6 Steve NFL
null
pn
41
Inserting in a Linked List Representing a Queue
  • Step 2 Attach the new node at the end of the
    list
  • tail.setNext( pn )

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
6 Steve NFL
null
head
tail
42
Inserting in a Linked List Representing a Queue
  • Step 3 Update tail
  • tail tail.getNext( )

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
7 Sarah Mario
6 Steve NFL
null
head
tail
43
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).

44
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.

45
Array Representing a Stack
  • There are three items on the stack

46
Our Stack after Inserting Player (6, Steve, NFL )
  • Now there are four items on the stack

47
Our Stack After Popping Once
  • Now there are three items on the stack. Player
    ( 6, Steve, NFL ) is not on the stack.

48
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
  • .

49
Constructor for our Stack
  • The constructor does two things
  • It instantiates the array, stack.
  • It initializes top to -1 to reflect that the
    stack is empty. If top were initialized to 0,
    then there would be an element on the stack, at
    index 0.
  • public ArrayStack( )
  • stack new PlayerSTACK_SIZE
  • top -1 // stack is empty

50
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 ) )

51
toString Method for our Stack
  • public String toString( )
  • String stackString ""
  • for ( int i top i gt 0 i-- )
  • stackString ( i " "
  • stacki "\n" )
  • return stackString

52
push Method for our Stack
  • public boolean push( Player p )
  • if ( !isFull( ) )
  • stacktop p
  • return true
  • else
  • return false

53
pop Method for our Stack
  • public Player pop
  • throws DataStructureException
  • if ( !isEmpty( ) )
  • return ( stacktop-- )
  • else
  • throw new DataStructureException
  • ( "Stack empty cannot pop" )
  • See Example 14.9 ArrayStack.java

54
Common ErrorTrap
  • Do not confuse the top of the stack with the last
    index in the array. Array elements with array
    indexes higher than top are not on the stack.

55
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.

56
Queue after Inserting First 5 Elements
  • // Player( 5, Ajay, Sonic ) was enqueued first.

57
Queue after Dequeueing Once
  • Element at index 0 is no longer usable.

58
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.

59
An Empty Queue

60
Enqueueing One Element

61
Enqueueing a Second Element

62
Enqueueing a Third Element

63
Enqueueing a Fourth Element

64
Dequeueing Once

65
Dequeueing Again

66
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

67
A Full Queue

68
Empty Queue
  • When the queue is empty, we also have the same
    relationship between front and back!
  • ( back 1 front ) QUEUE_SIZE 0

69
An Empty Queue

70
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.

71
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

72
Constructor for our Queue
  • The constructor does four things
  • 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 PlayerQUEUE_SIZE
  • front 0
  • back QUEUE_SIZE - 1
  • numberOfItems 0

73
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 )

74
toString Method for our Queue
  • public String toString( )
  • String queueString ""
  • if ( back gt front )
  • for ( int i front i lt back i )
  • queueString queuei "\n"
  • else
  • for ( int i front i lt QUEUE_SIZE i )
  • queueString queuei "\n"
  • for ( int i 0 i lt back i )
  • queueString queuei "\n"
  • return queueString

75
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.11 ArrayQueue.java

76
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" )

77
Common ErrorTrap
  • 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.

78
Implementing a Stack or a Queueas an Array vs as
a Linked List
79
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 use the key id.
  • Without loss of generality, we will consider a
    list sorted in ascending order.

80
Sorted Linked Lists
  • Here is an example of a sorted linked list of
    Player objects (the key is id )

8 Gino Diablo
7 Sarah Mario
5 Ajay Sonic
2 Jin Golf
null
head
81
PlayerSortedLinkedList Methods
82
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.

83
Inserting in the Middle or at the End of a
Sorted Linked List
  • Instantiate the new node.
  • Traverse the list to identify the location to
    insert the new node. Call the node before
    previous, and the node after current.
  • Attach the new node to current.
  • Attach previous to the new node.
  • Update the number of items.

84
Inserting in the Middle or at the End of a
Sorted Linked List
  • Our original linked list

8 Gino Diablo
7 Sarah Mario
5 Ajay Sonic
2 Jin Golf
null
head
85
Inserting in the Middle or at the End of a
Sorted Linked List
  • Step 1 Instantiate a new node
  • PlayerNode pn new PlayerNode( p )
  • // here, p is Player( 6, Steve, NFL )

8 Gino Diablo
7 Sarah Mario
5 Ajay Sonic
2 Jin Golf
null
head
6 Steve NFL
null
pn
86
Inserting in the Middle or at the End of a
Sorted Linked List
  • Step 2 Connect pn to current
  • pn.setNext( current )

8 Gino Diablo
7 Sarah Mario
5 Ajay Sonic
2 Jin Golf
null
previous
current
head
6 Steve NFL
pn
87
Inserting in the middle or at the end of a
Sorted Linked List
  • Step 3 Connect previous to pn
  • previous.setNext( pn )

8 Gino Diablo
7 Sarah Mario
5 Ajay Sonic
2 Jin Golf
null
previous
current
head
6 Steve NFL
pn
88
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.13 PlayerSortedLinkedListTest.java

89
Deleting from a Sorted Linked List
  • Our delete method is similar to the previous
    delete method of a linked list.
  • If the item 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.12 PlayerSortedLinkedList.java

90
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.

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

2 Jin Golf
92
Doubly Linked List
  • A doubly linked list looks like this

2 Jin Golf
8 Gino Diablo
5 Ajay Sonic
null
null
head
93
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.

94
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.

95
Our Original Doubly Linked List

2 Jin Golf
8 Gino Diablo
current
96
Inserting in a Doubly Linked List
  • Step 1 instantiate a new node ( pn )
  • PlayerNode pn new PlayerNode( p )

2 Jin Golf
8 Gino Diablo
current
6 Steve NFL
null
null
pn
97
Inserting in a Doubly Linked List
  • Step 2 Set next in pn to current
  • pn.setNext( current )

2 Jin Golf
8 Gino Diablo
current
6 Steve NFL
null
pn
98
Inserting in a Doubly Linked List
  • Step 3 Set next in node before current to pn
  • ( current.getPrevious( ) ).setNext( pn )

2 Jin Golf
8 Gino Diablo
current
6 Steve NFL
null
pn
99
Inserting in a Doubly Linked List
  • Step 4 Set previous in pn to node before
    current
  • pn.setPrevious( current.getPrevious( ) )

2 Jin Golf
8 Gino Diablo
current
6 Steve NFL
pn
100
Inserting in a Doubly Linked List
  • Step 5 Set previous in current to pn
  • current.setPrevious( pn )

2 Jin Golf
8 Gino Diablo
current
6 Steve NFL
pn
101
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.

102
Deleting in the Middle of a Doubly Linked List
  • Our original list
  • The Player with id 6 will be deleted.

2 Jin Golf
6 Steve NFL
8 Gino Diablo
current
103
Deleting in the Middle of a Doubly Linked List
  • Connect forward link of node before current to
    node after current
  • ( current.getPrevious( ) ).setNext(
    current.getNext( ) )

2 Jin Golf
6 Steve NFL
8 Gino Diablo
current
104
Deleting in the Middle of a Doubly Linked List
  • Connect backward link of node after current to
    node before current.
  • ( current.getNext( ) ).setPrevious
  • ( current.getPrevious( ) )
  • current is now unreachable, and is deleted.

2 Jin Golf
6 Steve NFL
8 Gino Diablo
current
105
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)

106
PlayerRecursiveLinkedList Methods
107
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

108
Inserting in a Recursively Defined Linked List
  • The original list, before inserting Player p
  • The list after inserting Player p

p1 r1

rest
first
p ned list)

p1 r1

first
rest
109
Inserting at the Beginning of a List
  • Instantiate the new node.
  • Attach the node to the beginning of the list.
  • Update head.
  • Update the number of items.

110
Deleting from a Recursively Defined Linked List
  • Our delete method deletes the first item on the
    list whose key value matches a given key value.
  • Our delete method is recursive.
  • There are three base cases
  • Empty list throw an exception.
  • The item to delete is the first one on the list
    delete it.
  • The item to delete is not the first one on the
    list and the rest of the list is empty throw an
    exception.
  • In the general case, we make a recursive call to
    try to delete from the rest of the list.
  • See Example 14.16 PlayerRecursiveLinkedList.java

111
Deleting the First Item in a Recursively Defined
Linked List
  • The original list, before deleting Player p

p ned list)

p1 r1

first
rest
112
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)

p1 r1

first
rest
113
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

first
rest
114
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.

115
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

116
Testing a Recursively Defined Linked List Class
  • When testing the insert method of a recursively
    defined linked list class, be sure to test all
    possibilities
  • inserting into an empty list.
  • inserting in a list of one element.
  • inserting in a list of two or more elements.
  • Traverse the list after each insert to verify
    that the item was properly inserted.
  • See Example 14.17 PlayerRecursiveLinkedListTest.ja
    va

117
Testing a Recursively Defined Linked List Class
  • When testing the delete method of a recursively
    defined linked list class, be sure to test all
    possibilities
  • failing to delete from an empty list
  • failing to delete from a non-empty list
  • deleting an element at the end of the list
  • deleting an element in the middle of the list
  • deleting the only element of the list
  • Traverse the list after each call to delete to
    verify that the item was properly deleted.
  • See Example 14.17 PlayerRecursiveLinkedListTest.ja
    va

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

119
Software Engineering Tip
  • When implementing methods of a recursively
    defined class, think in terms of implementing
    recursive methods.
Write a Comment
User Comments (0)
About PowerShow.com