Title: Java Programming: Program Design Including Data Structures
1Chapter 16 Linked Lists
Java Programming Program Design Including
Data Structures
2Chapter Objectives
- Learn about linked lists
- Study the basic properties of linked lists
- Explore the insertion and deletion operations on
linked lists - Discover how to build and manipulate a linked
list - Learn how to construct a doubly linked list
- Become aware of circular linked lists
3Linked Lists
- Linked list
- List of items, called nodes
- The order of the nodes is determined by the
address, called the link, stored in each node - Every node (except the last node) contains the
address of the next node - Components of a node
- Data stores the relevant information
- Link stores the address of the next node
4Linked Lists (continued)
Figure 16-1 Structure of a node
Figure 16-2 Linked list
5Linked Lists (continued)
- Head or first
- Holds the address of the first node in the list
- The info part on the node can be either a value
of a primitive type or a reference to an object - Class Node
- Represents nodes on a list
- It has two instance variables
- info (of type int, but it can be any other type)
- link (of type Node)
6Linked Lists (continued)
- Class Node
- public class Node
-
- public int info
- public Node link
-
- Notice that instance variables of the class Node
are declared as public. - Declaring them as public allows direct access to
these instance variables when traversing a linked
list, deleting / inserting a node in a linked
list.
7Linked List Some Properties
- Consider the following linked list
Memory addresses
Figure 16-4 Linked list with four nodes
8Linked List Some Properties (continued)
head.info the info of the node at the location
pointed to by head head.link the link of the
node at the location pointed to by
head head.link.info the info of the node at the
location pointed to by head.link
9Linked List Some Properties
- Now consider the statement
- current head
Figure 16-5 Linked list after current head
executes
10Linked List Some Properties (continued)
11Linked List Some Properties(continued)
- Now consider the statement
- current current.link
Figure 16-6 List after the statement
current current.link executes
12Linked List Some Properties (continued)
13Linked List Some Properties (continued)
14Traversing a Linked List
- Basic operations of a linked list that require
the link to be traversed - Search the list for an item
- Insert an item in the list
- Delete an item from the list
- You cannot use head to traverse the list
- You would lose the nodes of the list
- Use another reference variable of the same type
as head current
15Traversing a Linked List (continued)
- The following code traverses the list
- current head
- while (current ! null)
-
- //Process current
- current current.link
16Traversing a Linked List (continued)
- The following code outputs the data stored in
each node - current head
- while (current ! null)
-
- System.out.println(current.info )
- current current.link
17Item Insertion and Deletion
- Consider the following definition of a node
- public class Node
-
- public int info
- public Node link
-
- And the following variable declaration
- Node head, p, q, newNode
18Insertion
- Consider the following linked list
- You want to create a new node, called newNode,
with info 50 and insert it after p
Figure 16-7 Linked list before item insertion
19Insertion (continued)
- The following statements create and store 50 in
the info field of a new node - newNode new Node() //create newNode
- newNode.info 50 //store 50 in the new
node
Figure 16-8 Create newNode and store 50 in it
20Insertion (continued)
- The following statements insert the node in the
linked list at the required place - newNode.link p.link
- p.link newNode
- The sequence of statements to insert the node is
very important - If you reverse the sequence of the statements,
you will not get the desired result
21Insertion (continued)
Figure 16-9 List after the statement
newNode.link p.link executes
Figure 16-10 List after the statement
p.link newNode executes
22Insertion (continued)
- Using two reference variables, you can simplify
the code somewhat - Consider the following
Figure 16-12 List with reference variables p and q
23Insertion (continued)
- The following statements insert newNode between p
and q - newNode.link q
- p.link newNode
- or
- p.link newNode
- newNode.link q
- The order in which these statements execute does
not matter
24Insertion (continued)
Figure 16-13 List after the statement
p.link newNode executes
Figure 16-14 List after the statement
newNode.link q executes
25Deletion
- Consider the following linked list
- You want to delete node with info 34
Figure 16-15 Node to be deleted is with info 34
26Deletion (continued)
- The following statement removes the nodes from
the list - p.link p.link.link
Figure 16-16 List after the statement
p.link p.link.link executes
27Deletion (continued)
- Previous statement removed the node
- However, the memory may still be occupied by this
node - Systems automatic garbage collector reclaims
memory occupied by unreferenced nodes - Use System.gc() to run the garbage collector
28Deletion (continued)
- Using two reference variables, you can simplify
the code somewhat - Consider the following statements
- q p.link
- p.link q.link
- q null // no need for q any more
- System.gc()
29Deletion (continued)
Figure 16-17 List after the statement
q p.link executes
Figure 16-18 List after the statement
p.link q.link executes
30Building a Linked List
- You can build a list in two ways forward or
backward - Forward manner
- A new node is always inserted at the end of the
linked list - Backward manner
- A new node is always inserted at the beginning of
the linked list
31Building a Linked List Forward
- You need three reference variables of node
- One to point to the front of the list
- Cannot be moved
- One to point to the last node of the list
- One to create the new node
- Next two slides show the code for creating a
linked list forward
32Building a Linked List Forward (continued)
Node buildListForward() Node first, newNode,
last int num System.out.println(Enter
integers ending with -999) num
console.nextInt() first null while
(num ! -999) newNode new Node()
newNode.info num newNode.link
null if (first null)
first newNode last newNode
else last.link
newNode last newNode
num console.nextInt() //end while
return first //end buildListForward
See textbook p.1029 - 1031 Data 2, 15, 8, 24,
34 List first ? 2? 15? 8? 24? 34? null
Ref. variable last going forward Ref. variable
first always point to the first node
33Building a Linked List Backward
- You only need two reference variables
- One to point to the front of the list
- Changes each time a new node is inserted
- One to create the new node
- Next slide shows the code for creating a linked
list backward
See textbook p.1029 1032 Data 2, 15, 8, 24,
34 List first ? 34? 24? 8?15?
2?null
34Building a Linked List Backward (continued)
See textbook p.1029 1032 Data 2, 15, 8, 24,
34 List first ? 34? 24? 8?15?
2?null
Node buildListBackward() Node first,
newNode int num System.out.println(Ente
r integers ending with -999) num
console.nextInt() first null while
(num ! -999) newNode new Node()
//create a node newNode.info num
//store the data in newNode
newNode.link first //put newNode at the
beginning of the list first newNode
//update the head of the list, num
console.nextInt() //get the next number
return first //end buildListBackward
Ref. variable first going backward Ref. variable
last not used here
35Linked List as an ADT
Proceed to slide 62
Figure 16-27 UML class diagram of the interface
LinkedListADT
36Linked List as an ADT (continued)
- There are two types of linked lists sorted and
unsorted - The algorithms to implement some of the
operations differ for sorted and unsorted lists - Therefore, define the LinkedListClass as an
abstract class - LinkedListClass has two derived classes
- UnorderedLinkedList
- OrderedLinkedList
37Structure of Linked List Nodes
- Each node of a linked list must keep track of the
data as well as the next node in the list - The node has two instance variables
- Define the class LinkedListNode as an inner class
of LinkedListClass - Simplify operations such as insert and delete
- LinkedListNode is defined as protected and generic
38Structure of Linked List Nodes (continued)
Figure 16-28 UML class diagram of the class
LinkedListNode and the outer-inner
class relationship
39Instance Variables of the Class LinkedListClass
- Instance variables
- protected LinkedListNodeltTgt first //variable to
store the - //address of
the first - //node of the
list - protected LinkedListNodeltTgt last //variable to
store the - //address of
the last - //node of the
list - protected int count //variable to store the
number of - //nodes in the list
40Linked List Iterators
- An iterator is an object that produces each
element of a collection one element at a time - An iterator has at least two methods hasNext and
next - hasNext
- Determines whether there is a next element in the
collection - next
- Gives access to the next element in the list
41Linked List Iterators (continued)
Figure 16-29 UML class diagram of the class
LinkedListIterator and the outer-inner
class relationship
42Constructors and Instance Methods of the class
LinkedListClass
Figure 16-30 UML class diagram of the class
LinkedListClass
43isEmptyList
- isEmptyList method
- public boolean isEmptyList()
-
- return (first null)
44Default Constructor
- Default constructor
- public LinkedListClass()
-
- first null
- last null
- count 0
45initializeList
- initializeList method
- public void initializeList()
-
- first null
- last null
- count 0
46print List
- print method
- public void print()
-
- LinkedListNodeltTgt current //variable to
traverse - //the list
- current first //set current so that it
points to - //the first node
- while (current ! null) //while more data to
print -
- System.out.print(current )
- current current.link
-
- //end print
47Length of the List
- length method
- public int length()
-
- return count
48Retrieving Data of the First and the Last Node
- front and back methods
- public T front()
-
- return first.info
-
- public T back()
-
- return last.info
49clone
- Returns a clone of the list
- The current implementation of the clone method
makes a shallow copy of the list
50Definition of the class LinkedListClass
- Definition of the class LinkedListClass
- public abstract class LinkedListClassltTgt
implements LinkedListADTltTgt -
- //Place the definition of the class
LinkedListNodeltTgt here. - //Place the definition of the class
LinkedListIteratorltTgt - //here.
- //Place the definition of the nonabstract
methods and the - //abstract methods here.
51Unordered Linked List
Figure 16-31 UML class diagram of the class
UnorderedLinkedList and the
inheritance hierarchy
52search
- search method
- public boolean search(T searchItem)
-
- LinkedListNodeltTgt current //variable to
traverse - //the list
- boolean found
- current first //set current to point to
the first - //node in the list
- found false //set found to false
- while (current ! null !found) //search
the list - if (current.info.equals(searchItem))
//item is found - found true
- else
- current current.link //make current
point to - //the next
node - return found
53insertFirst
- insertFirst method
- public void insertFirst(T newItem)
-
- LinkedListNodeltTgt newNode //variable to
create the - //new node
- newNode
- new LinkedListNodeltTgt(newItem, first)
//create and - //insert
newNode before - //first
- first newNode //make first point to the
- //actual first node
- if (last null) //if the list was empty,
newNode is - //also the last node in
the list - last newNode
- count //increment count
54insertLast
- insertLast method
- public void insertLast(T newItem)
-
- LinkedListNode newNode //variable to create
the new node - newNode new LinkedListNode(newItem, null)
//create newNode - if (first null) //if the list is empty,
newNode is - //both the first and last
node -
- first newNode
- last newNode
-
- else //if the list is not empty, insert
newNode after last -
- last.link newNode //insert newNode after
last - last newNode //set last to point to
the actual last node -
- count
- //end insertLast
55deleteNode
- You should consider four cases
- The list is empty
- The first node is the node to be deleted
- The node to be deleted is somewhere in the list
- The list does not contain the node to be deleted
56Ordered Linked Lists
Figure 16-39 UML class diagram of the class
OrderedLinkedList and the
inheritance hierarchy
57search
- search method
- public boolean search(T searchItem)
-
- LinkedListNodeltTgt current //variable to
traverse the list - boolean found
- current first //set current to point to
the first node in the list - found false //set found to false
- while (current ! null !found ) //search
the list -
- ComparableltTgt temp (ComparableltTgt)
current.info - if (temp.compareTo(searchItem) gt 0)
- found true
- else
- current current.link //make
current point to the next node -
- if (found)
- found current.info.equals(searchItem)
- return found
58insert
- To insert an item in an ordered linked list
- First find the place for the new item
- Insert the item in the list
- You should consider three cases
- The list is initially empty
- The list is not empty and the new item is smaller
than the smallest item in the list - The list is not empty and the new item is larger
than the first item in the list
59insertFirst
- insertFirst method
- public void insertFirst(T newItem)
-
- insert(newItem)
60insertLast
- insertLast method
- public void insertLast(T newItem)
-
- insert(newItem)
- //end insertLast
61deleteNode
- You should consider four cases
- The list is initially empty
- The item to be deleted is contained in the first
node of the list - The item to be deleted is somewhere in the list
- The list is not empty, but the item to be deleted
is not in the list
62Doubly Linked Lists (p. 1072)
- Linked list in which every node has a next
pointer and a back pointer - A doubly linked list can be traversed in either
direction, if a reference variable to the last
node is given
Figure 16-48 Doubly linked list
63Doubly Linked Lists (continued)
- Class DoublyLinkedListNode
- public class DoublyLinkedListNodeltTgt implements
Cloneable -
- T info
- DoublyLinkedListNodeltTgt next
- DoublyLinkedListNodeltTgt back
-
- //place constructors and methods here
64Doubly Linked Lists (continued)
- Instance variables of the class DoublyLinkedList
- protected int count //variable to store
the - //number of nodes
- protected DoublyLinkedListNodeltTgt first
//reference variable - //to
point to the - //first
node - protected DoublyLinkedListNodeltTgt last
//reference variable - //to
point to the - //last
node
See p.1081 for list object and node object
65Default Constructor
- Default constructor
- public DoublyLinkedList()
-
- first null
- last null
- count 0
66isEmptyList
- Method isEmptyList
- public boolean isEmptyList()
-
- return (first null)
67initializeList
- Method initializaList
- (for reinitializing existing lists)
- public void initializeList()
-
- first null
- last null
- count 0
68Length of the List
- Method length
- public int length()
-
- return count
69print
- Method print
- public void print()
-
- DoublyLinkedListNodeltTgt current//reference
variable - //to traverse
the list - current first //set current to point to
- //the first node
- while (current ! null)
-
- System.out.print(current )
- current current.next
- //end while
- //end print
70reversePrint List
- Method reversePrint
- public void reversePrint()
-
- DoublyLinkedListNodeltTgt current //reference
variable to - //traverse
the list - current last //set current to point to
the last node - while (current ! null)
-
- System.out.print(current.info )
- current current.back
- //end while
- //end reversePrint
71search List
- Method search
- public boolean search(T searchItem)
-
- boolean found
- DoublyLinkedListNodeltTgt current //reference
variable to traverse the list - found false
- current first
- while (current ! null !found)
-
- ComparableltTgt temp (ComparableltTgt)
current.info - if (temp.compareTo(searchItem) gt 0)
- found true
- else
- current current.next
-
- if (found)
- found current.info.equals(searchItem)
//test for equality - return found
- //end search
for nondecreasing list
for nondecreasing list only
72The First and the Last Element
- Methods front and back
- public T front()
-
- return first.info
-
- public T back()
-
- return last.info
73Insert
- You should consider four cases
- Insertion in an empty list (need to change the
values of first and last) - Insertion at the beginning of a nonempty list
(need to change the values of first) - Insertion at the end of a nonempty list
- Insertion somewhere in an nonempty list (Cases 3
and 4 are similar, see P.1081 for the diagram)
74Delete Node
- You should consider four cases
- The list is empty
- The item to be deleted is in the first node of
the list - The item to be deleted is somewhere in the list
- The item to be deleted is not in the list
- (See P.1083-1084 for case 3)
75Circular Linked Lists
- A linked list in which the last node points to
the first node - It is convenient to make first point to the last
node
Figure 16-56 Circular linked list with more than
one node
76Programming Example Video Store
- The program should perform these operations
- Rent a video
- Return a video
- Create a list of videos owned by the store
- Show the details of a particular video
- Print a list of all videos in the store
- Check whether a particular video is in the store
- Maintain a customer database
- Print a list of all videos rented by each customer
77Chapter Summary
- Linked list
- List of nodes in which the order of the nodes is
determined by the link stored in each node - Has a reference head to the first node
- Some operations include
- Traversing a list
- Inserting a list in the list
- Deleting a list from the list
78Chapter Summary (continued)
- Linked list can be either sorted or unsorted
- Doubly linked list
- Linked list in which every node has a next and a
back pointer - Operations are similar to those in a linked list
- Circular linked list
- Linked list as a linked list in which the last
node points to the first node