hampehs! what the hell is it?€¦ · web viewjava ( version 2 ) has several standard list...
TRANSCRIPT
CHAPTER 7 : LINKED LIST
Objectives :
At the end of this chapter, you should have learnt
a) how to implement a singly linked list
b) how to display contents of a linked list
c) how to delete a specified node from a linked list
d) how to insert a node into a specified position in a linked list
e) the difference between array-based and reference-based implementation
f) how to differentiate between a singly linked list and a doubly linked list
g) circular linked list
7 - 1
CS214 CHAPTER 7: LINKED LISTS
1) LINKED LIST
Linked list is a data structure that consists of related items that are linked to
one another.
A linked-list could be implemented either using
i. array-based implementation
ii. reference-based implementation
Java ( version 2 ) has several standard list classes, including ArrayList
( implemented with an array ), and LinkedList ( implemented with dynamic
allocated memory ). Both of these classes implement the List interface, which
means they share many of the same methods.
Some of the common methods in the standard list classes :
Method Description
add ( Object o )
clear ()
contains ( Object o )
equals ( Object o )
get ( int index )
indexOf ( Object o )
Appends the given object to the end of the list
Empties the list
Returns true if the given object is in the list
Returns true if this list is equal to the given
list
Returns the object at the given position in the
list
Returns the position of the first occurrence of
the given object, or –1 if the object is not in
the list
7 - 2
CS214 CHAPTER 7: LINKED LIST
Method Description
isEmpty()
remove ( int index )
set ( int index, Object element )
size()
Returns true if the list is empty
Removes the object at the given position in
the list
Changes the value of the object at the given
position in the list
Returns the number of elements in the list
Please take note : in this chapter, the focus is on the reference-based
implementation of a linked list
2) ARRAY-BASED vs REFEERENCE-BASED IMPLEMENTATION
Array-based
i. a good choice if the list is small
ii. have a fixed size
iii. increasing the size of a resizeable array can waste storage and
time
iv. requires less memory than a reference-based implementation
v. can access array items directly with equal access time
7 - 3
Programming and Problem Solving with Java, James M Slack
Copyright 2000 Brooks/Cole, Thompson Learning
CS214 CHAPTER 7: LINKED LISTS
Reference-based
i. do not have fixed size
ii. list can grow or shrink during run-time
iii. the item after an array item is implied, but in a linked list, an
item explicitly references the next item
iv. must traverse a linked list to access its nth node
v. insertion and deletion in a linked list is easier
3) REFERENCE-BASED SINGLY LINKED LIST
Each component in a linked list is called a node and it contains both data and
the ‘link’ to the next item. Typically such links are Java reference variables.
Each node of the linked list can be implemented as an object. For example, if
you want to create a linked list of integers, you could use the following class
definition :
7 - 4
public class IntegerNode {
private int item;
private IntegerNode next;
public void setItem ( int newItem ) {
item = newItem;
}
public int getItem () {
return item;
}
CS214 CHAPTER 7: LINKED LIST
To use the above class :
Illustration 1 :
7 - 5
Cont.
public void setNext ( IntegerNode nextNode ) {
next = nextNode;
}
public IntegerNode getNext() {
return next;
}
} // end of IntegerNode
Data Abstraction and Problem Solving with Java : Walls and Mirror, Frank M
Carrano & Janet J Prichard, Copyright 2001 Addison Wesley Longman, Inc
IntegerNode num1 = new IntegerNode ();
IntegerNode num2 = new IntegerNode ();
num1.setItem (10); // set item in the first node
num2.setItem (20); // set item in the second node
num1.setNext(num2); // link the nodes
10 20num1
num2
CS214 CHAPTER 7: LINKED LISTS
A node declaration for a linked list of objects
You can use the above class as follows :
7 - 6
public class Node {
private Object item;
private Node next;
public Node ( Object newItem ) {
item = newItem;
next = null;
}
public Node ( Object newItem, Node nextNode );
item = newItem;
next = nextNode;
}
public void setItem ( Object newItem ) {
item = newItem;
}
public Object getItem () {
return item;
}
public void setNext ( Node nextNode ) {
next = nextNode;
}
public Node getNext () {
return next;
}
}
Data Abstraction and Problem Solving with Java : Walls and Mirror, Frank M
Carrano & Janet J Prichard, Copyright 2001 Addison Wesley Longman, Inc
CS214 CHAPTER 7: LINKED LIST
4) DISPLAYING THE CONTENTS OF A LINKED LIST
Suppose that you have the following linked list
In this diagram, list is a reference variable that is external to the linked list,
whereas the next data fields are internal reference variables within the nodes of
the list. The variable list simply allows you to access the list’s beginning.
Java statements to display the data in a linked list :
7 - 7
Node newNode = new Node ( new Integer ( 6 ) ) ;
Node first = new Node ( new Integer ( 9 ), n );
newNode 6
9first
10 20list 13
item next item next
null
for ( Node curr = list; curr != null; curr = curr.getNext() ) {
System.out.println ( curr.getItem () ) ;
}
CS214 CHAPTER 7: LINKED LISTS
The above Java statements require you to keep track the current position
within the linked list. Thus curr must reference the first node. To do this,
simply copy list into curr by writing :
Node curr = list;
To move to the current position to the next node :
curr = curr.getNext();
5) INSERTING A NODE INTO A SPECIFIED POSITION OF A LINKED
LIST
Suppose that you want to insert value 11 into the linked list :
In this diagram, you insert the new node, which the reference variable
newNode references, between the two node that prev and curr reference. You
can accomplish the insertion by using the following pair of assignment
statements :
newNode.setNext ( curr );
prev.setNext ( newNode );
7 - 8
10 20list 13
item next
11newNode
prev curr
CS214 CHAPTER 7: LINKED LIST
You create a new node that references the item as follows :
newNode = new Node ( item );
To insert a node at the beginning of a list, you must make list reference the
new node, and the new node must reference the node that had been at the
beginning of the list.
newNode.setNext ( list );
list = newNode;
To insert a node at the end of a list, as you traverse the list, curr becomes null
as it moves past the end of the list. Notice that, if curr is null and prev
references the last node on the list, the following statements will insert the
node at the end of the list.
newNode.setNext ( curr );
prev.setNext ( newNode );
To insert a node in a linked list, it involves 3 high-level steps :
i. determine the point of insertion
ii. create a new node and store the new data in it
iii. connect the new node to the linked list by changing references
7 - 9
prev = null;
curr = head;
while ( curr != null && newValue > curr.getItem ()) {
prev = curr;
curr = curr.getNext();
}
CS214 CHAPTER 7: LINKED LISTS
Sample program ( Linked.java ) :
7 - 10
import java.io.*;// make sure that you have the IntegerNode class stored in IntegerNode.java
class Linked { static void displayList ( IntegerNode list ) { System.out.print("List->"); for ( IntegerNode curr = list; curr != null; curr = curr.getNext()) { System.out.print( curr.getItem() + "->"); } System.out.print("nil"); System.out.print("\n\n"); } public static void main( String args[] ) throws IOException { IntegerNode curr, prev,newNode, list = null; BufferedReader br; int newValue;
do { br = new BufferedReader ( new InputStreamReader( System.in)); System.out.print("Enter a value [0 to stop]: " ); String str = br.readLine(); newValue = Integer.parseInt(str);
if ( newValue != 0 ) { newNode = new IntegerNode(newValue); prev = null; curr = list; while ( curr != null && newValue > curr.getItem()) { prev = curr; curr = curr.getNext(); } // insert at the beginning if ( prev == null ) { newNode.setNext(list); list = newNode; } // insert in the middle or at the end if ( prev != null && list != null ) { newNode.setNext(curr); prev.setNext(newNode); } displayList(list); } // end of if newValue = 0 } while (newValue != 0 ); } }
CS214 CHAPTER 7: LINKED LIST
6) DELETING A SPECIFIED NODE FROM A LINKED LIST
Suppose you want to delete a particular node, say node with value 13, from a
linked list.
In this diagram, you can delete node N, which curr references, by altering the
value of the reference next in the node that precedes N. Thus, bypassing N on the
chain. The dashed line indicates the old reference value.
Take note that this reference change does not directly affect node N. Since curr
still references node N, the node remains in existence. However, the node has
effectively been deleted from the linked list.
To delete the node that curr references :
prev.setNext ( curr.getNext() );
To delete the first item on the list :
list = list.getNext();
7 - 11
10 20list 13
item next
prev curr
node N
CS214 CHAPTER 7: LINKED LISTS
To delete a node in a linked list, it involves 3 high-level steps :
i. Locate the node that you want to delete
ii. Disconnect this node from the linked list by changing
references
iii. Return the node to the system
Sample program ( comment on the following program ) :
7 - 12
import java.io.*;class LinkDelete { static IntegerNode curr, prev,newNode,list; static BufferedReader br; static int newValue;
static void displayList ( IntegerNode list ) { System.out.print("List->"); for ( IntegerNode curr = list; curr != null; curr = curr.getNext()) { System.out.print( curr.getItem() + "->"); } System.out.print("nil"); System.out.print("\n\n"); } static void addItem () throws IOException{ br = new BufferedReader( new InputStreamReader( System.in)); System.out.print("Add number : " ); String str = br.readLine(); newValue = Integer.parseInt(str); newNode = new IntegerNode(newValue);
prev = null; curr = list; while ( curr != null && newValue > curr.getItem()) { prev = curr; curr = curr.getNext(); } // insert at the beginning if ( prev == null ) { newNode.setNext(list);
list = newNode;
}
CS214 CHAPTER 7: LINKED LIST
7 - 13
// insert in the middle or at the end if ( prev != null && list != null ) { newNode.setNext(curr); prev.setNext(newNode); } displayList(list); } // end of addItem
static void deleteItem() throws IOException{ br = new BufferedReader ( new InputStreamReader( System.in)); System.out.print("Delete number : " ); String str = br.readLine(); newValue = Integer.parseInt(str);
prev = null; curr = list; while ( curr != null && newValue != curr.getItem()) { prev = curr; curr = curr.getNext(); } // delete first item in the list if ( prev == null ) { list = list.getNext(); } // delete other nodes in the list if (prev != null && list != null ) { prev.setNext(curr.getNext()); } displayList(list); }// end of deleteItem
public static void main( String args[] ) throws IOException { list = null; do { br = new BufferedReader ( new InputStreamReader( System.in)); System.out.print("[1]Add [2]Delete [0] to stop]: " ); String str = br.readLine(); newValue = Integer.parseInt(str); switch ( newValue ) { case 1 : addItem(); break; case 2 : deleteItem(); break; case 0 : break; default : System.out.println("No such option."); } } while (newValue != 0 ); } // end of main()}
CS214 CHAPTER 7: LINKED LISTS
7) CIRCULAR LINKED LIST
In circular linked list, the next reference of the list’s last node references the
first node, instead of containing null.
Every node in a circular linked list references a successor, so you can start at
any node and traverse the entire list.
To display data in a circular linked list :
7 - 14
10 20list 13
if ( list != null ) {
Node curr = list;
do {
System.out.println ( curr.getItem() );
curr = curr.getNext;
} while ( curr != list );
}
CS214 CHAPTER 7: LINKED LIST
8) DOUBLY LINKED LIST
Each node in a doubly linked list references both its predecessor and its
successor.
Doubly linked list facilitates searching an item or items in the list since you
may traverse the list forward or backward easily.
To insert a node, say with value 25, in the doubly linked list
7 - 15
10list 20 30 40
precede
v
next
item
10list 20 30 40
25
newnode
curr
CS214 CHAPTER 7: LINKED LISTS
Assuming that newNode references a new node, the following Java statements
performs the insertion of the new node once its position is found.
To delete a particular node, say node with value 20, from the doubly linked list
7 - 16
:
newNode.setnext (curr );
newNode.setPrecede ( curr.getPrecede());
curr.setPrecede ( newNode );
newNode.getPrecede().setNext ( newNode );
10list 20 30 40
:
// delete the node that curr references
curr.getPrecede().setNext( curr.getNext());
curr.getNext().setPrecede ( curr.getPrecede() );
curr
CS214 CHAPTER 7: LINKED LIST
9) EXERCISES
a) Given
i. Write Java statements that create the above linked list. Starting
with an empty linked list, first create and attach a node for M,
then create and attach a node for J, and finally create and attach
a node for E.
ii. Repeat part (i) but instead create and attach nodes in the order
E, J, M.
b) Consider this list :
Suppose that prev references the first node in this list and curr references the
second node.
i. Write Java statements that delete the second node and return it
to the system
ii. Now assume that curr references the first node of the remaining
two nodes of the original list. Write Java statements that delete
the first node and return it to the system
7 - 17
E J M
list
P T Y
list
prev curr
CS214 CHAPTER 7: LINKED LISTS
iii. Now list references the only node that is left in the list. Write
Java statements that insert a new node that contains B into the
list so that the list remains sorted.
c) Write a Java method that displays only the nth integer in a linked list of
integers. Assume that n > 1 and that the linked list contains at least n nodes.
d) Write a method to count the number of items in a linked list
i. iteratively
ii. recursively
e) Write a method that displays the largest integer in a linked list of integers.
10) REFERENCES
Programming and Problem Solving with Java, James M Slack, Copyright 2000
Brooks/Cole, Thompson Learning. ( Chapter 12 )
Data Abstraction and Problem Solving with Java : Walls and Mirror, Frank M
Carrano & Janet J Prichard, Copyright 2001 Addison Wesley Longman, Inc
( Chapter 4 )
7 - 18