Download Linked Lists

Document related concepts

Quadtree wikipedia , lookup

Interval tree wikipedia , lookup

B-tree wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Binary search tree wikipedia , lookup

Linked list wikipedia , lookup

Transcript
Chapter 16: Linked Lists
Java Programming:
Program Design Including Data Structures
Linked 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
Java Programming: Program Design Including Data Structures
2
Linked Lists
Class…
Interface…
Interface…
Interface…
Object
Iterable
Cloneable
Serializable
Class…
Interface…
AbstractCollection
Collection
Class…
Interface…
Interface…
AbstractList
List
Queue
Class…
Interface…
AbstractSequentialList
Deque
Class…
LinkedList
COSC 237
© R.G. Eyer , 2012
3
Linked Lists (continued)
Figure 16-1 Structure of a node
Figure 16-2 Linked list
Java Programming: Program Design Including Data Structures
4
Linked 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)
Java Programming: Program Design Including Data Structures
5
Linked 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
Java Programming: Program Design Including Data Structures
6
Linked List: Properties
Figure 16-4 Linked list with four nodes
7
Linked List: Properties
Figure 16-5 Linked list after current = head; executes
Java Programming: Program Design Including Data Structures
8
Linked List: Properties
 Consider the statement current = current.link;
Figure 16-6 After the statement current = current.link; executes
Java Programming: Program Design Including Data Structures
9
Traversing 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
Java Programming: Program Design Including Data Structures
10
Traversing a Linked List
 The following code traverses the list
current = head;
while (current != null) {
//Process current
current = current.link;
}
Java Programming: Program Design Including Data Structures
11
Traversing a Linked List
 The following code outputs the data stored in each
node
current = head;
while (current != null) {
System.out.println(current.info + “ “);
current = current.link;
}
Java Programming: Program Design Including Data Structures
12
Item 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;
Java Programming: Program Design Including Data Structures
13
Insertion
 Consider the following linked list
Figure 16-7 Linked list before item insertion
 You want to create a new node with info 50 and
insert it after p
Java Programming: Program Design Including Data Structures
14
Insertion (continued)
 The following statements create and store 50 in the
info field of a new node
newNode = new Node();
newNode.info = 50;
//create newNode
//store 50 in the new node
Figure 16-8 Create newNode and store 50 in it
Java Programming: Program Design Including Data Structures
15
Insertion (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
Java Programming: Program Design Including Data Structures
16
Insertion (continued)
Figure 16-9 List after the statement
newNode.link = p.link; executes
Figure 16-10 List after the statement
p.link = newNode; executes
Java Programming: Program Design Including Data Structures
17
Insertion (continued)
 Using two reference variables, you can simplify the
code somewhat
 Consider the following
Figure 16-12 List with reference variables p and q
Java Programming: Program Design Including Data Structures
18
Insertion (continued)
 The following code inserts newNode between p & q
newNode.link = q;
p.link = newNode;
or
p.link = newNode;
newNode.link = q;
 The order in which these statements execute does not
matter
Java Programming: Program Design Including Data Structures
19
Insertion (continued)
Figure 16-13 List after the statement
p.link = newNode; executes
Figure 16-14 List after the statement
newNode.link = q; executes
Java Programming: Program Design Including Data Structures
20
Deletion
 Consider the following linked list
Figure 16-15 Node to be deleted is with info 34
 You want to delete node with info 34
Java Programming: Program Design Including Data Structures
21
Deletion (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
Java Programming: Program Design Including Data Structures
22
Deletion (continued)
 Previous statement removed the node
 However, the memory may still be occupied by this
node
 System’s automatic garbage collector reclaims
memory occupied by unreferenced nodes
 Use System.gc(); to run the garbage collector
Java Programming: Program Design Including Data Structures
23
Deletion (continued)
 Using two reference variables, you can simplify the
code somewhat
 Consider the following statements
q = p.link;
p.link = q.link;
q = null;
System.gc();
Java Programming: Program Design Including Data Structures
24
Deletion (continued)
Figure 16-17 List after the statement
q = p.link; executes
Figure 16-18 List after the statement
p.link = q.link; executes
Java Programming: Program Design Including Data Structures
25
Building 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
Java Programming: Program Design Including Data Structures
26
Building a Linked List Forward
 You need three reference variables
 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
Java Programming: Program Design Including Data Structures
27
Building a Linked List Forward
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
Java Programming: Program Design Including Data Structures
28
Building 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
Java Programming: Program Design Including Data Structures
29
Building a Linked List Backward
Node buildListBackward() {
Node first, newNode;
int num;
System.out.println(“Enter 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 front of list
first = newNode;
// update the head of the list
num = console.nextInt(); // get the next number
}
return first;
} // end buildListBackward
Java Programming: Program Design Including Data Structures
30
Linked List as an ADT
Figure 16-27 UML class diagram of the interface LinkedListADT
Java Programming: Program Design Including Data Structures
31
Linked 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
Java Programming: Program Design Including Data Structures
32
Structure 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
Java Programming: Program Design Including Data Structures
33
Structure of Linked List Nodes
(continued)
Figure 16-28 UML class diagram of the class LinkedListNode
and the outer-inner class relationship
Java Programming: Program Design Including Data Structures
34
Instance Variables of the Class
LinkedListClass
 Instance variables
protected LinkedListNode<T> first; // variable to store the
// address of the first
// node of the list
protected LinkedListNode<T> 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
Java Programming: Program Design Including Data Structures
35
Linked 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
Java Programming: Program Design Including Data Structures
36
Linked List Iterators (continued)
Figure 16-29 UML class diagram of the class LinkedListIterator
and the outer-inner class relationship
Java Programming: Program Design Including Data Structures
37
Constructors and Instance Methods
of the class
LinkedListClass
Figure 16-30 UML class diagram of the class LinkedListClass
Java Programming: Program Design Including Data Structures
38
isEmptyList
 isEmptyList method
public boolean isEmptyList() {
return (first == null);
}
Java Programming: Program Design Including Data Structures
39
Default Constructor
 Default constructor
public LinkedListClass() {
first = null;
last = null;
count = 0;
}
Java Programming: Program Design Including Data Structures
40
initializeList
 initializeList method
public void initializeList() {
first = null;
last = null;
count = 0;
}
Java Programming: Program Design Including Data Structures
41
print List
 print method
public void print() {
LinkedListNode<T> current; // traverse variable
current = first; // set current to points to 1st node
while (current != null) { // while more data to print
System.out.print(current + “ “);
current = current.link;
}
} // end print
Java Programming: Program Design Including Data Structures
42
Length of the List
 length method
public int length() {
return count;
}
Java Programming: Program Design Including Data Structures
43
Retrieving Data of the First and the
Last Node
 front and back methods
public T front() {
return first.info;
}
public T back() {
return last.info;
}
Java Programming: Program Design Including Data Structures
44
clone
 Returns a clone of the list
 The current implementation of the clone method
makes a shallow copy of the list
Java Programming: Program Design Including Data Structures
45
Definition of the class
LinkedListClass
 Definition of the class LinkedListClass
public abstract class LinkedListClass<T> implements
LinkedListADT<T> {
//Place the definition of the class LinkedListNode<T> here.
//Place the definition of the class LinkedListIterator<T>
//here.
//Place the definition of the nonabstract methods and the
//abstract methods here.
}
Java Programming: Program Design Including Data Structures
46
Unordered Linked List
 Derive the class UnorderedLinkedList from the
abstract class LinkedListClass and implement
the operations:
 search()
 insertFirtst()
 insertLast()
 deleteNode()
Java Programming: Program Design Including Data Structures
47
Unordered Linked List
Figure 16-31 UML class diagram of the class UnorderedLinkedList
and the inheritance hierarchy
Java Programming: Program Design Including Data Structures
48
Definition of the class
UnorderedLinkedList
 Definition of the class UnorderedLinkedList
public class UnorderedLinkedList<T> extends LinkedListClass<T> {
}
Java Programming: Program Design Including Data Structures
49
search
 search method
public boolean search(T searchItem) {
LinkedListNode<T> current;
// traverse variable
boolean found;
current = first;
found = false;
// set current to point to 1st node
// initialize found to false
while (current != null && !found) //search the list
if (current.info.equals(searchItem))
found = true; // item found
else
// make current point to next node
current = current.link;
return found;
}
Java Programming: Program Design Including Data Structures
50
insertFirst
 insertFirst method
public void insertFirst(T newItem) {
LinkedListNode<T> newNode;
newNode = new LinkedListNode<T>(newItem, first);
// insert newNode before first
first = newNode;
// make first point to the
//
actual first node
if (last == null)
// if the list was empty, newNode is
last = newNode;
//
also the last node in the list
count++;
// increment count
}
Java Programming: Program Design Including Data Structures
51
insertLast
 insertLast method
public void insertLast(T newItem) {
LinkedListNode newNode; //variable to create the new node
newNode = new LinkedListNode(newItem, null);
if (first == null) {
// if the list is empty, newNode is
first = newNode; //
both the first and last node
last = newNode;
}
else {
// if list is not empty, insert newNode after last
last.link = newNode; // insert newNode after last and set
last = newNode;
//
last to point to new last node
}
count++;
} // end insertLast
Java Programming: Program Design Including Data Structures
52
deleteNode
 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
Java Programming: Program Design Including Data Structures
53
Ordered Linked Lists
 Derive the class OrderedLinkedList from the
abstract class LinkedListClass and implement
the operations:
 search()
 insert()
 insertFirtst()
 insertLast()
 deleteNode()
 Note: Assume that elements are
arranged in ascending order.
Java Programming: Program Design Including Data Structures
54
Ordered Linked Lists
Figure 16-39 UML class diagram of the class OrderedLinkedList
and the inheritance hierarchy
Java Programming: Program Design Including Data Structures
55
Definition of the class
OrderedLinkedList
 Definition of the class OrderedLinkedList
public class OrderedLinkedList<T> extends LinkedListClass<T> {
}
Java Programming: Program Design Including Data Structures
56
search
 search method

stop the search as soon as we find a node in the list with info greater than or
equal to the search item
public boolean search(T searchItem) {
LinkedListNode<T> current; // variable to traverse the list
boolean found;
current = first; // set current to point to 1st node in list
found = false;
// set found to false
while (current != null && !found ) { // search the list
Comparable<T> temp = (Comparable<T>) current.info;
if (temp.compareTo(searchItem) >= 0)
found = true;
else // make current point to the next node
current = current.link;
}
if (found)
found = current.info.equals(searchItem);
return found;
}
Java Programming: Program Design Including Data Structures
57
insert
 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
Java Programming: Program Design Including Data Structures
58
insertFirst and insertLast
 insertFirst and insertLast methods
public void insertFirst(T newItem) {
insert(newItem);
}
public void insertLast(T newItem) {
insert(newItem);
}
Java Programming: Program Design Including Data Structures
59
deleteNode
 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
Java Programming: Program Design Including Data Structures
60
Doubly Linked Lists
 Linked list in which every node has a next pointer
and a back pointer
 A doubly linked list can be traversed in either
direction
Figure 16-48 Doubly linked list
Java Programming: Program Design Including Data Structures
61
Doubly Linked List ADT
 Interface DoublyLinkedListADT
public interface DoublyLinkedListADT<T> extends Cloneable {
public Object clone();
public boolean isEmptyList();
public void initializeList();
public int length();
public void print();
public void reversePrint();
public boolean search(T searchItem);
public T front();
// the first node of the list
public T back();
// the last node of the list
public void insertNode(T insertItem);
public void deleteNode(T deleteItem);
}
Java Programming: Program Design Including Data Structures
62
Doubly Linked List
 Class DoublyLinkedList<T>
public class DoublyLinkedList<T> implements
DoublyLinkedListADT<T> {
protected DoublyLinkedListNode<T> first;
protected DoublyLinkedListNode<T> last;
protected int count;
// place definitions of DoublyLinkedListNode<T> and
// DoublyLinkedListIterator<T>
public class DoublyLinkedListNode<T> implements Cloneable {
…
}
public class DoublyLinkedListIterator<T> {
…
}
}
Java Programming: Program Design Including Data Structures
63
Doubly Linked List Node
 Class DoublyLinkedListNode<T>
public class DoublyLinkedListNode<T>
implements Cloneable {
T info;
DoublyLinkedListNode<T> next;
DoublyLinkedListNode<T> back;
// place constructors and methods here
}
Java Programming: Program Design Including Data Structures
64
Doubly Linked List Iterator
 Class DoublyLinkedListIterator<T>
public class DoublyLinkedListIterator<T> {
protected DoublyLinkedListNode<T> current;
protected DoublyLinkedListNode<T> previous;
// place constructors and methods here
}
Java Programming: Program Design Including Data Structures
65
Doubly Linked List
 Instance variables of the class DoublyLinkedList<T>
// variable to store the number of nodes
protected int count;
//reference variable to point to the first node
protected DoublyLinkedListNode<T> first;
//reference variable to point to the last node
protected DoublyLinkedListNode<T> last;
Java Programming: Program Design Including Data Structures
66
Default Constructor
 Default constructor of the class DoublyLinkedList<T>
public DoublyLinkedList() {
first= null;
last = null;
count = 0;
}
Java Programming: Program Design Including Data Structures
67
isEmptyList
 Method isEmptyList() of the class
DoublyLinkedList<T>
public boolean isEmptyList() {
return (first == null);
}
Java Programming: Program Design Including Data Structures
68
initializeList
 Method initializaList of the class
DoublyLinkedList<T>
public void initializeList() {
first = null;
last = null;
count = 0;
}
Java Programming: Program Design Including Data Structures
69
Length of the List
 Method length of the class DoublyLinkedList<T>
public int length() {
return count;
}
Java Programming: Program Design Including Data Structures
70
print
 Method print
public void print() {
// reference variable to traverse the list
DoublyLinkedListNode<T> current;
// set current to point to the first node
current = first;
while (current != null) {
System.out.print(current + “ “);
current = current.next;
}
}
Java Programming: Program Design Including Data Structures
71
reversePrint List
 Method reversePrint of the class
DoublyLinkedList<T>
public void reversePrint() {
// reference variable to traverse the list
DoublyLinkedListNode<T> current;
current = last;
// set current to point to the last node
while (current != null) {
System.out.print(current.info + “
current = current.back;
}
“);
}
Java Programming: Program Design Including Data Structures
72
search List
 Method search of the class DoublyLinkedList<T>
public boolean search(T searchItem) {
boolean found = false;
DoublyLinkedListNode<T> current = first;
while (current != null && !found) {
Comparable<T> temp = (Comparable<T>) current.info;
if (temp.compareTo(searchItem) >= 0)
found = true;
else
current = current.next;
}
if (found)
found = current.info.equals(searchItem);
return found;
}
Java Programming: Program Design Including Data Structures
73
The First and the Last Element
 Methods front and back of the class
DoublyLinkedList<T>
public T front() {
return first.info;
}
public T back() {
return last.info;
}
Java Programming: Program Design Including Data Structures
74
Insert
 You should consider four cases




Insertion in an empty list
Insertion at the beginning of a nonempty list
Insertion at the end of a nonempty list
Insertion somewhere in an nonempty list
public void insertNode(T insertItem) {
}
Java Programming: Program Design Including Data Structures
75
Delete 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
public void deleteNode(T deleteItem) {
}
Java Programming: Program Design Including Data Structures
76
Circular 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
Java Programming: Program Design Including Data Structures
77
Programming 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
Java Programming: Program Design Including Data Structures
78
Key Terms
• Linked list: A collection of components, called nodes.
• Node: A data structure that has two components: the info and the link.
• Link: The component of a node that stores the address of the next node in
a list.
• Head: A reference variable that stores the address of the first node in a
list.
• First: See head.
• Iterator: An object that produces each element of a collection, such as a
linked list, one element at a time. An iterator typically has at least two
methods, hasNext and next.
• Doubly linked list: A linked list in which every node has a next pointer
and a back pointer.
• Circular linked list: A linked list in which the last node points to the first
node.
Java Programming: Program Design Including Data Structures
79
Chapter 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
Java Programming: Program Design Including Data Structures
80
Chapter 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
Java Programming: Program Design Including Data Structures
81