linked lists
TRANSCRIPT
LINKED LISTS
Dr. Yasir Faheem and Mr. Salman Niazi Lecture 3
Overview
Linked List
Operations on Linked List CreateList
EmptyList
PrintList
InsertElement
DeleteElement
DestroyList
FindElement
RetrieveElement
ModifyElement
Linked List
In a linked list representation, the data elements
are not constrained to be stored in sequential order;
rather, the individual elements are stored
“somewhere” in memory.
The order of the elements is maintained by explicit
links between them.
Daud Rabia Maria Javed
List/Start
Linked List (Contd)
node node node node
Info Next Info Next Info Next Info Next
Each node contains two fields;
Data field for staring information and
Next address field (a reference), which contains the
address of the next node in the list.
Linked List(Contd)
Since, the list is linear, the link field of the last node
contains NULL.
NULL: a special pointer value that says, “ This pointer
doesn’t point to anything”.
An external pointer (e.g. List/Start) contains address
of the first node in the list.
List=NULL if the list is empty
Info Next
0x80010
Info Next
0x80031
Info Next
NULL List= 0x80017
0x80017 0x80010 0x80031
Linked List (Contd)
Nodes are created and destroyed dynamically, using
new operator. We do not have to declare an array
large enough to store maximum number of elements.
Using a linked structure streamlines the algorithms
that manipulate the elements. For example , we can
avoid all of the data movement that was necessary to
insert and delete into a sequential list.
Linked List (Contd)
With a linked representation , the existing elements
stay where they are (in the memory) as others are
added and deleted.
We only have to change the links that establish the
order of the elements.
Daud Rabia Maria Javed
List
Kashif newNode
Linked List Implementation
The data structure that will hold the elements of the list is called Node.
Let’s declare node :-
Linked List Implementation(Contd) public class LinkedList<Listable>{
protected class ListNode{ protected Listable info; // The info in a list node protected ListNode next; // A link to the next node on the list } protected ListNode list; // Reference to the first node on the list protected int numItems; // Number of elements in the list protected
ListNode PredLoc_, Loc_; // References to be used by Find() method public LinkedList(); //constructor public boolean isEmpty(); // checks if the list is empty or not public int lengthIs(); // Determines the number of elements on this list public Listable retrieve (Listable item); // Returns a copy of the list element with the
same key as item public boolean isThere (Listable item); // Determines if element matching item is on this
list public void insertAtFront (Listable item); // Adds a new item at the front of this list public void insertAtEnd (Listable item); // Adds a new item to the end of this list public void insertInMiddle (int position, Listable item); // Adds a new item into the middle
of this list public void delete (Listable item); // Deletes the element of this list whose key matches
item's key public void printList(); //prints all elements of the list
} //end of LinkedList class
Creating/Initializing the List
To create an empty list , we just have to set List to
NULL.
public LinkedList() // Creates an empty list object { numItems = 0; list = null; currentPos = null; }
EmptyList Operation
If the List ( external reference to the list ) is equal
to NULL , then the list is empty , and EmptyList
Operation returns true.
Otherwise list has some elements, and EmptyList
Operation returns false.
public boolean isEmpty(){ // Determines whether this list is full if(this.list==null) return true; else return false; }
PrintList Operation
The PrintList Operation , prints out all the elements of the linked list.
The general algorithm to do this , is :-
PrintList
Location = Start of the list
WHILE (more elements in list) DO
Print elements Info(Location)
Location = Next (Location)
PrintList Operation
To access the beginning of the list , we initialize the
reference location by setting it equal to the external
reference, List.
How do we know if there are more elements in the
List ?
When location reference is equal to the special value
NULL in the Next field of the last node , we know that
we have reached the end of the list.
PrintList Operation
Daud Rabia Maria Javed
list
public void printList(){ //prints all elements of the list ListNode location=list; int count=0; if(list==null) System.out.println("List is Empty"); else{ System.out.println("Printing List"); for(location=list;location!=null;location=location.next){ System.out.println(location.info+" is "+(++count)+"th item"); } } }
15
FindElement Operation
Here’s the algorithm for FindElement.
FindElement
Location = Start of list
WHILE ( Key(Location) < KeyValue AND more nodes in list ) DO
Location= Next(Location)
Set Location and PredLoc based on loop terminating conditions.
16
FindElement Operation
There are three loop terminating conditions, and we
set Location and PredLoc accordingly.
1. Location = NULL :- If we reach the end of the list
without finding an element whose key is as large as
KeyValue , then the element is not in the list.
• Location correctly has the value of NULL. In this case , if
we want to insert an element into the list , it belongs at
the end of the list.
• So PredLoc is set to point to the last node.
17
FindElement Operation (Contd)
Find Zahid
Daud Rabia Maria Javed
List
PredLoc
Location Null
18
FindElement Operation
2. Location != NULL and Key(Location) = KeyValue :
• In this case , we have found the element within the
list.
• Location correctly points to the node with the
specified key.
• And PredLoc is set to point to the preceding node.
19
FindElement Operation
Find Maria
Daud Rabia Maria Javed
List
PredLoc
Location
20
FindElement Operation
3. Location != NULL and KeyLocation != KeyValue
• In this case , we have found the location where the
element belongs , but it isn’t in the list.
• Location is reset to NULL to indicate that the element
was not found ,
• And PredLoc is set to point to the last node whose
key was less than KeyValue.
21
FindElement Operation
Find Kashif
Daud Rabia Maria Javed
List
PredLoc
Location NULL
22
FindElement Operation
We will initialize Location to List , and PredLoc to
NULL.
Inside the loop ,we will advance both the pointers.
As the Location will move ahead, PredLoc will follow
the Location.
FindElement Operation
//find method finds key values in a sorted list only public void find(Listable key) // find link with given key {
initialize_PredLoc_Loc(); // set temporary references PredLoc_ and //Loc_ to null
Loc_=list; //Initialize to Loc_; PredLoc_ already refers to null if (Loc_==null) //list is empty PredLoc_=Loc_=null return ; //Search for node containing Key until : // 1 : we reach the KeyValue's logical place in the list // 2 : we reach the end of the list boolean moreToSearch=true; while(moreToSearch && Loc_!=null){ if(Loc_.info.compareTo(key)<0){ PredLoc_=Loc_; //advance PredLoc_ & Loc_ references Loc_=Loc_.next; } else moreToSearch=false; }
FindElement Operation
// If Location does not point to a node containing // KeyValue, reset Location to NULL if(Loc_!=null){ if(Loc_.info!=key) Loc_=null; } } //end of find Method
Find Maria Find Kashif
Two Possibilities
•If key being searched is found in the linked list (Find Maria example), then
Location(Loc_) refers correctly to the node containing key = “Maria”.
•If key is not found in the list (Find Kashif example), then Location (Loc_) should refer
to null.
25
The Insertion Operation
This operation allows new values to be inserted into
the linked list
In order to insert a new value, first we have to
find/determine its position in the list.
The second task is to create space for the new
element.
Space is created dynamically at run time , using built-in
operator new.
The third task is to properly link the new node into
the link list
Inserting elements into linked List
There are four cases to consider :-
Inserting into an empty list.
Inserting before the “first node” of the list.
Inserting into the “middle” of the list.
Inserting after the “last node” in the list.
27
Insertion into an Empty List
If linked list is empty then external reference list contains null
Create space for new node
ListNode newNode = new ListNode();// create a new node and save its address location
in the reference newNode
newNode.info = “Kashif”;
Reference list should now point to the new node.
newNode.Next = list/null;
list = newNode; //external reference list now points towards node Kashif
Kashif newNode
List null
Kashif List
Insertion at the Front of the List
Insert Bilal at the beginning of the list
List Kashif
Bilal
List Kashif Bilal + =
29
InsertElement Operation
We can join the cases of inserting a value into an empty list and at the front of the list in a single insertion method.
Case 1: Inserting into an Empty List
Next(NewNode) = NULL
List=NewNode
Case 2: Inserting at the Front of the List
Next(NewNode) = List
List = NewNode
Insertion is straight forward , we put List in the next of the new node, and new node in the List.
The List pointer thus points to the List with new element added at the front of the list.
When the list is empty , List ( pointer to the List ) is NULL , therefore we can combine first and second case.
Insertion at the Front of the List
This method inserts a new value into an empty list
and also at the front of the existing list
public void insertAtFront (Listable item){ // Adds a new item at front of the list ListNode newNode = new ListNode(); newNode.info = (Listable)item; newNode.next = list; list = newNode; numItems++; }
Insertion at the End of the List
Insert Zahid into the list
Daud Maria Javed
List
Rabia
Zahid
PredLoc
Insertion at the End of the List
public void insertAtEnd (Listable item){ // Adds a new item to the end of this list if(this.lengthIs()==0){ this.insertAtFront((Listable)item); return; } else{ ListNode newNode = new ListNode(); newNode.info = (Listable)item; ListNode location=list; while(location.next!=null) location=location.next; newNode.next = location.next; // or we can say newNode.next = null location.next = newNode; numItems++; } }
Insertion into the Middle of the List
Insert Kashif in the linked list
Daud Rabia Maria Javed
List
Kashif newNode PredLoc
Insertion into the Middle of the List public void insertInMiddle (int position, Listable item){ if(position > (this.numItems+1)){ System.out.println("Invalid position: Aborting"); } else if(position==1){ //Insertion at the beginning of the list this.insertAtFront((Listable)item); return; } else if (position==(this.numItems+1)){ //Insertion at the end of the list this.insertAtEnd((Listable)item); } else{ //insertion into the middle of the list ListNode newNode = new ListNode(); newNode.info = (Listable)item; int count=1; ListNode location=list; while((count+1)!=position && location.next!=null){ //Find reference of the predecessor node of the new node to be inserted location=location.next; ++count; } newNode.next = location.next; location.next = newNode; numItems++; } } //End of insertInMiddle Method
A single Insert Method for inserting
a value in a Sorted Linked List
You now know how to insert a value at the front of
the list, in the middle of the list and at the end of
the list.
You also have find(key) method which finds a key
item in the linked list, and based on whether or not
the key exists in the list, returns references in Loc_
and PredLoc_ references.
Let’s now write a method InsertSorted(key), which
first finds logical position of the key item in the
sorted list using find(item) method, and then inserts
the key where it belongs in the list.
InsetSorted() Method
//this method is used to insert values into a sorted list public void insertSorted(Listable key){ find(key); // find location of the key ListNode NewNode = new ListNode(); NewNode.info=key; if(PredLoc_==null){ //insert in empty list or at front. NewNode.next=list; list=NewNode; //list now refers to Newnode } else{ //Insertion in middle or at the end of the list NewNode.next=PredLoc_.next; PredLoc_.next=NewNode; } }
37
InsertElement Operation
How do we know if the list is empty or if we are
inserting at the beginning of the list ?
How do we know if we are inserting at the end of
the list ?
38
DeleteElement Operation
When deleting an element from the list , there are
four cases to consider :-
Deleting the only list element , leaving the list empty.
Deleting the “first” node.
Deleting the “middle” node.
Deleting the “last” node.
DeleteElement Operation
This operation allows the user to delete an element
from the list if it exists.
In this operation, the first task is to find the node
containing the element to be deleted.
If found, the node containing that element should be
deleted from the linked list.
Before that, Next field of the predecessor of the to
be deleted node should be properly re-linked to its
new successor in the linked list.
40
DeleteElement Operation
Delete first list node( Delete Daud)
Location
Daud Maria Javed
List
Rabia
41
DeleteElement Operation
Delete “middle” node ( Delete Maria )
Maria will be accessed via Location.Next.
Location
Daud Maria Javed
List
Rabia
42
DeleteElement Operation
Delete last node ( Delete Rabia )
Location.next refers towards Rabia node.
Location.next=Location.next.next; //equivalent her to
location.next = null since
location.next.next refers to null
Location
Daud Maria Javed
List
Rabia
Null
deleteElementSorted Method
public void deleteElementSorted(Listable key){ find(key); //find reference of the node containing key value // & reference to its predecessor i.e. Loc_ & PredLoc_ respectively if (Loc_==null) System.out.println("Deletion Failed: Key not Found in the list"); else { if(PredLoc_==null){ //if deleting first element of the list, then updated list reference list=Loc_.next; Loc_=null; } else{ PredLoc_.next=Loc_.next; } System.gc(); // explicitly calling garbage collector } }
DestroyList Operation
To destroy a linked list, the dynamically allocated
space used by the elements of the list must be freed
(done by JVM’s garbage collector).
The easiest approach to do this, is to unlink each of
the list elements, and free the space used.
Info Next
0x80010
Info Next
0x80031
Info Next
NULL List= 0x80017
0x80017 0x80010 0x80031
45
The End