SlideShare a Scribd company logo
1
List ADT & Linked Lists
2
List
A Flexible structure, because can grow
and shrink on demand.
Elements can be:
 Inserted
 Accessed
 Deleted
At any position
3
List
Lists can be:
 Concatenated together.
 Split into sublists.
Mostly used in Applications like:
 Information Retrieval
 Programming language translation
 Simulation
4
List
A List is a sequence of zero or more
elements of a given type (say
elementtype)
Represented by a comma-separated
sequence of elements:
a1, a2,…an
Where,
n >= 0 and each ai is of type
elementtype.
5
List
if n>= 1,
a1 is the first element
an is the last element
if n = 0,
we have an empty list
6
List
The elements of a list can be linearly ordered.
⇒ai precedes ai+1 for i = 1,2,3…n-1
ai follows ai-1 for i = 2,3,4…n
The element ai is at position i.
END(L) will return the position following
position n in an n-element list L.
Position END(L) has a varying distance as the
list grows and shrinks, all other positions
have a fixed distance from the beginning of
the list.
7
Common Operations on List ADT
1. INSERT(x,p,L): Insert x at position p in list L. If
list L has no position p, the result is undefined.
2. LOCATE(x,L): Return the position of x on list
L.
3. RETRIEVE(p,L): Return the element at
position p on list L.
4. DELETE(p,L): Delete the element at position p
on list L.
5. NEXT(p,L): Return the position following p on
list L.
8
Common Operations on List ADT
6. PREVIOUS(p,L): Return the position
preceding position p on list L.
7. MAKENULL(L): Causes L to become an
empty list and returns position END(L).
8. FIRST(L): Returns the first position on the list
L.
9. PRINTLIST(L): Print the elements of L in order
of occurrence.
9
Implement a Linked Structure Using an Array
1 3 4 10
I data[I] next[I]
0 3 6
1 * *
2 1 0
3 10 -1
4 * *
5 * *
6 4 3
Need a start link.
start
end
How to insert,
delete, and
append?
10
Linked Structure Using an Array
With a free list
1 3 4 10
I data[I] next[I]
0 3 6
1 * 4
2 1 0
3 10 -1
4 * -1
5 * 1
6 4 3
Data_start
end
Free list
Free_start
11
Linked Structure Using an Array
I data[I] next[I]
0 * 6
1 * 4
2 * 0
3 * 5
4 * -1
5 * 1
6 * 3
Free_start
end
Free list
12
Linked Lists
Pointer Based Implementation of Linked List ADT
Dynamically allocated data structures can be linked together to form
a chain.
A linked list is a series of connected nodes (or links) where each
node is a data structure.
A linked list can grow or shrink in size as the program runs.
This is possible because the nodes in a linked list are dynamically
allocated.
13
If new information needs to be added to the list, the program -
a) Allocates another node
b) Inserts it into the series.
If a piece of information is to be deleted from the list, the program -
a) Deletes the node containing the information
Advantages of Linked Lists over Arrays
Linked lists are more complex to code and manage than arrays,
but they have some distinct advantages.
a) A linked list can easily grow and shrink in size.
14
(The programmer doesn’t need to know how many nodes will be
in the list. They are created in memory as needed).
b) Speed of insertion or deletion from the list.
e.g. with an array, to insert an element, requires all elements beyond
the insertion point to be moved forward one position to make room
for the new element.
Similarly, to delete an element, requires all elements after
the insertion point to be moved back one position to close the gap.
When a node is inserted, or deleted from a linked list, none of the
other nodes have to be moved!!!!
15
Composition of a Linked List
Each node in the linked list contains -
a) One or more members that represent data (e.g. inventory records,
customer names, addresses, telephone numbers, etc).
b) A pointer, that can point to another node.
Data Members Pointer
16
A linked list is called “linked” because each node in the series
(i.e. the chain) has a pointer to the next node in the list, e.g.
List Head
NULL
a) The list head is a pointer to the first node in the list.
b) Each node in the list points to the next node in the list.
c) The last node points to NULL (the usual way to signify the end).
Note, the nodes in a linked list can be spread out over the memory.
17
Declarations
How to declare a linked list in C++?
Step 1) Declare a data structure for the nodes.
e.g. the following struct could be used to create a list where each
node holds a float -
struct ListNode
{
float value;
ListNode *next;
};
18
a) The first member of the ListNode struct is a float called value.
It is to hold the node’s data.
b) The second member is a pointer called next.
It is to hold the address of any object that is a ListNode struct.
Hence each ListNode struct can point to the next one in the list.
The ListNode struct contains a pointer to an object of the same type
as that being declared. It is called a self-referential data structure.
This makes it possible to create nodes that point to other nodes of
the same type.
19
Step 2) Declare a pointer to serve as the list head, e.g
ListNode *head;
Before you use the head pointer, make sure it is initialized to NULL,
so that it marks the end of the list.
Once you have done these 2 steps (i.e. declared a node data structure,
and created a NULL head pointer, you have an empty linked list.
The next thing is to implement operations with the list.
Linked List Operations
There are 5 basic linked list operations -
20
1) Appending a node
2) Traversing a list
3) Inserting a node
4) Deleting a node
5) Destroying the list
We will implement this Linked List ADT (abstract data type) that
performs basic linked list operations using the ListNode structure and
head pointer declared earlier. We use the following class
declaration -
class FloatList
{
private:
// Declare a structure for the list
struct ListNode
{
float value;
struct ListNode *next;
};
ListNode *head; // List head pointer
21
public:
FloatList(void) // Constructor
{ head = NULL; }
~FloatList(void); // Destructor
void appendNode(float);
void insertNode(float);
void deleteNode(float);
void displayList(void);
};
Note, the constructor initializes the head pointer to NULL,
establishing an empty linked list.
The class has members to append, insert, delete and display (all)
nodes.
The destructor destroys the list by deleting all its nodes.
22
We now examine these functions individually -
1) Appending a Node to the List
To append a node to a linked list, means adding it to the end of the list.
The appendNode member function accepts a float argument, num.
The function will -
a) allocate a new ListNode structure
b) store the value in num in the node’s value member
c) append the node to the end of the list
This can be represented in pseudo code as follows-
23
a) Create a new node.
b) Store data in the new node.
c) If there are no nodes in the list
Make the new node the first node.
Else
Traverse the List to Find the last node.
Add the new node to the end of the list.
End If.
The actual C++ code for the above pseudo code is -
24
void FloatList::appendNode(float num)
{
ListNode *newNode, *nodePtr;
// Allocate a new node & store num
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
// If there are no nodes in the list
// make newNode the first node
if (!head)
head = newNode;
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
}
25
We examine this important piece of code in detail.
The function declares the following local variables -
ListNode *newNode, *nodePtr;
a) The newNode pointer will be used to allocate and point to the new
node.
b) The nodePtr pointer will be used to travel down the linked list,
looking for the last node.
The next few statements -
i) create a new node
ii) store num in its value member.
26
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
The last statement above is important. This node will become the
last node in the list, so its next pointer must point to NULL.
Now test the head pointer to see if there are any nodes already
in the list. If head points to NULL, we make the new node the
first in the list.
Do this by making head point to the new node, i.e.
if(!head)
head = newNode;
27
But, if head does not point to NULL, then there must already
be nodes in the list.
The else part must then contain code to -
a) Find the end of the list
b) Insert the new node.
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
28
The code uses nodePtr to travel down the list. It does this by
assigning nodePtr to head.
nodePtr = head;
A while loop is then used to traverse (i.e. travel through) the list,
looking for the last node (that will have its next member pointing
to NULL).
while(nodePtr->next)
nodePtr = nodePtr->next;
Now the nodePtr is pointing to the last node in the list, so make its
next member point to newNode.
nodePtr->next = newNode;
29
This appends newNode at the end of the list.
Remember, newNode->next already points to
NULL.
// This program demonstrates a simple append
// operation on a linked list.
#include <iostream.h>
#include "FloatList.h”
void main(void)
{
FloatList list;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
}
(This program displays no output.)
30
We step through the above program, observing how the appendNode
function builds a linked list to store the 3 argument values.
The head pointer is automatically initialized to 0 (NULL), indicating
the list is empty.
The first call to appendNode passes 2.5 as the argument.
A new node is allocated in memory.
2.5 is copied into its value member, and NULL is assigned to its
next pointer.
31
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
The next statement to execute is the following if statement.
if (!head)
head = newNode;
There are no more statements to execute, so control returns to
function main.
Since head points to NULL, then the condition !head is true, so
the statement, head = newNode is executed, making newNode
the first node in the list.
32
There are no more statements to execute, so control returns to the
function main.
In the second call to appendNode, 7.9 is passed as the argument.
Again, the first 3 statements create a new node, which stores the
argument in the node’s value member, and assigns its next pointer
to NULL. Visually this is -
33
Since head no longer points to NULL, the else part of the if statement
is executed.
else // Otherwise, insert newNode at end
{ // Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
The first statement in the else block assigns the value in head
to nodePtr. So, nodePtr and head point to the same node.
34
Look now at the next member of the node that nodePtr points at.
Its value is NULL, so nodePtr->next also points to NULL.
So, nodePtr is already at the end of the list, so the while loop
terminates.
The last statement, nodePtr->next = newNode, causes
nodePtr->next to point to the new node. This appends newNode to
the end of the list, as shown -
35
The third time appendNode is called, 12.6 is passed as argument.
Again, the first 3 statements create a node with the argument stored
in the value member.
Now, the else part of the if statement executes. Again nodePtr is
made to point to the same node as head.
36
Since nodePtr->next is not NULL, the while loop will execute.
After its first iteration, nodePtr will point to the second node in the
list.
The while loop’s conditional test will fail after the first iteration
because nodePtr->next now points to NULL.
The last statement nodePtr->next = newNode causes
nodePtr->next to point to the new node. This appends newNode
to the end of the list, as shown -
37
The above is the final state of the linked list.
2) Traversing a Linked List
The previous function appendNode, used a while loop that
traverses, or travels through the linked list.
We now demonstrate the displayList member function, that
traverses the list, displaying the value member of each node.
38
The following pseudocode represents the algorithm -
Assign list head to node pointer
While node pointer is not NULL
Display the value member of the node pointed to by node pointer.
Assign node pointer to its own next member.
End While.
The actual C++ code is -
39
void FloatList::displayList(void)
{
ListNode *nodePtr;
nodePtr = head;
while(nodePtr)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}
40
// This program calls the displayList member function.
// The funcion traverses the linked list displaying
// the value stored in each node.
#include <iostream.h>
#include "FloatList.h"
void main(void)
{
FloatList List;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
list.displayList();
}
Program 17-2 Output
2.5
7.9
12.6
41
Usually, when an operation is performed on some or all of the nodes
in a linked list, a traversal algorithm is used.
We will see variations of this traversal algorithm used throughout
this chapter.
3) Inserting a Node
Inserting a node in the middle of a list is more complicated than
appending a node.
Assume all values in the list are sorted, and you want all new values
to be inserted in their proper position (preserving the order of the
list).
We use the same ListNode structure again, with pseudo code.
42
This pseudocode shows the algorithm to find the new node’s
proper position in the list, and inserting it there.
It is assumed the nodes already in the list are ordered.
Create a new node.
Store data in the new node.
If there are no nodes in the list
Make the new node the first node.
Else
Find the first node whose value is greater than or equal
the new value, or the end of the list (whichever is first).
Insert the new node before the found node, or at the end of
the list if no node was found.
End If.
43
The code for the traversal algorithm is shown below. (As before, num
holds the value being inserted into the list.)
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is less
// than num.
while (nodePtr != NULL && nodePtr->value < num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
The entire insertNode function begins on the next slide.
44
The new algorithm finds the first node whose value is greater than
or equal to the new value.
The new node is then inserted before the found node.
This requires two pointers during the traversal -
a) One to point to the node being inspected
b) The other to point to the previous node.
The code above shows this traversal algorithm.
Num holds the value being inserted into the list.
45
void FloatList::insertNode(float num)
{
ListNode *newNode, *nodePtr, *previousNode;
// Allocate a new node & store Num
newNode = new ListNode;
newNode->value = num;
// If there are no nodes in the list
// make newNode the first node
if (!head)
{
head = newNode;
newNode->next = NULL;
}
else // Otherwise, insert newNode.
{
// Initialize nodePtr to head of list
nodePtr = head;
The code below uses the pointers nodePtr and previousNode.
previousNode always points to the node before the one pointed to by
nodePtr. The entire insertNode function is shown below.
46
// Skip all nodes whose value member is less
// than num.
while (nodePtr != NULL && nodePtr->value < num)
{
previousNode = nodePtr;
} nodePtr = nodePtr->next;
// If the new mode is to be the 1st in the list,
// insert it before all other nodes.
if (previousNode == NULL)
{
head = newNode;
newNode->next = nodePtr;
}
else
{
previousNode->next = newNode;
newNode->next = nodePtr;
}
}
}
47
// This program calls the displayList member function.
// The function traverses the linked list displaying
// the value stored in each node.
#include <iostream.h>
#include "FloatList.h”
void main(void)
{
FloatList list;
// Build the list
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
// Insert a node in the middle
// of the list.
list.insertNode(10.5);
// Dispay the list
list.displayList();
}
48
Program Output
2.5
7.9
10.5
12.6
As in previous program, this program calls the appendNode function 3
times to build the list with the values 2.5, 7.9, 12.6
The insertNode function is called with argument 10.5
In insertNode, the new node is created, and the function argument
is copied to its value member.
49
Since the list already has nodes stored in it, the else part of the if
statement will execute.
It begins by assigning nodePtr to Head, i.e.
Since nodePtr is not NULL, and nodePtr->value is less than num,
the while loop will iterate.
During the iteration, previousNode is made to point to the node
that nodePtr is pointing to. nodePtr is then advanced to point to
the next node. i.e.
50
The loop does its test once more. Since nodePtr is not NULL, and
nodePtr->value is less than num, the loop iterates a second time.
During the second iteration, both previousNode and nodePtr are
advanced by one node in the list, i.e.
51
This time, the loop’s test will fail, because nodePtr is not less than
num.
The statements after the loop will execute, which cause
previousNode->next to point to newNode, and newNode->next
to point to nodePtr, i.e.
52
This leaves the list in its final state. The nodes (you will see if
you follow the links from the head pointer to NULL) are stored
in the order of their value members.
Deleting a Node
This requires 2 steps -
a) Remove the node from the list without breaking the links
created by the next pointers.
b) Delete the node from memory.
53
The deleteNode member function searches for a node with a
particular value and deletes it from the list.
It uses an agorithm similar to the insertNode function.
The two node pointers nodePtr and previousPtr are used to
traverse the list (as before).
When nodePtr points to the node to be deleted, previousNode->next
is made to point to nodePtr->next.
This removes the node pointed to by nodePtr from the list.
The final step is to free the memory used by the node using the
delete operator.
54
void FloatList::deleteNode(float num)
{
ListNode *nodePtr, *previousNode;
// If the list is empty, do nothing.
if (!head)
return;
// Determine if the first node is the one.
if (head->value == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
// Initialize nodePtr to head of list
nodePtr = head;
55
// Skip all nodes whose value member is
// not equal to num.
while (nodePtr != NULL && nodePtr->value !=
num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
// Link the previous node to the node after
// nodePtr, then delete nodePtr.
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
// This program demonstrates the deleteNode member function
#include <iostream.h>
#include "FloatList.h“
void main(void)
{
FloatList list;
56
// Build the list
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
cout << "Here are the initial values:n";
list.displayList();
cout << endl;
cout << "Now deleting the node in the middle.n";
cout << "Here are the nodes left.n";
list.deleteNode(7.9);
list.displayList();
cout << endl;
cout << "Now deleting the last node.n";
cout << "Here are the nodes left.n";
list.deleteNode(12.6);
list.displayList();
cout << endl;
cout << "Now deleting the only remaining node.n";
cout << "Here are the nodes left.n";
list.deleteNode(2.5);
list.displayList();
}
57
Program Output
Here are the initial values:
2.5
7.9
12.6
Now deleting the node in the middle.
Here are the nodes left.
2.5
12.6
Now deleting the last node.
Here are the nodes left.
2.5
Now deleting the only remaining node.
Here are the nodes left.
58
To show how deleteNode works, we do a step through of the call
to delete the node with value 7.9
Look at the else part of the 2nd if statement. It is here the function
does its thing, since the list is not empty, and the first node does
not contain 7.9
The node pointers nodePtr and previousPtr are used to traverse the
list (as with the insertNode function).
The while loop terminates when the value 7.9 is found. When this
happens the list and other pointers are in the following state -
59
Then the following statement executes -
previousNode->next = nodePtr->next;
This causes the links in the list to bypass the node that nodePtr
points to.
The node still exists in memory, but it is removed from the list.
60
The bypassed node is destroyed with the statement delete nodePtr;
Destroying the List
Use the class’s destructor to release all the memory used by the list.
It does this by stepping through the list, deleting each node, one by one.
61
FloatList::~FloatList(void)
{
ListNode *nodePtr, *nextNode;
nodePtr = head;
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
Note the use of nextNode instead of previousNode.
The nextNode pointer is used to hold the position of the next node
in the list, so it will be available after the node pointed to by
nodePtr is deleted.
Ad

More Related Content

What's hot (20)

Singly link list
Singly link listSingly link list
Singly link list
Rojin Khadka
 
Case study windows
Case study windowsCase study windows
Case study windows
Padam Banthia
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
Sujith Kumar
 
Merge sort
Merge sortMerge sort
Merge sort
Vidushi Pathak
 
Binary Search
Binary SearchBinary Search
Binary Search
kunj desai
 
Lec 01 basic concepts
Lec 01 basic conceptsLec 01 basic concepts
Lec 01 basic concepts
Abdul Khan
 
Architecture of operating system
Architecture of operating systemArchitecture of operating system
Architecture of operating system
Supriya Kumari
 
Array in c
Array in cArray in c
Array in c
Ravi Gelani
 
linked list
linked list linked list
linked list
Mohaimin Rahat
 
CS8391 Data Structures Part B Questions Anna University
CS8391 Data Structures Part B Questions Anna UniversityCS8391 Data Structures Part B Questions Anna University
CS8391 Data Structures Part B Questions Anna University
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
javaicon
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
Praveen M Jigajinni
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
Poojith Chowdhary
 
Airline Reservation System
Airline Reservation SystemAirline Reservation System
Airline Reservation System
Sahil Talwar
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Hardware and Software parallelism
Hardware and Software parallelismHardware and Software parallelism
Hardware and Software parallelism
prashantdahake
 
Ppt bubble sort
Ppt bubble sortPpt bubble sort
Ppt bubble sort
prabhakar jalasutram
 
Kernel (OS)
Kernel (OS)Kernel (OS)
Kernel (OS)
عطاءالمنعم اثیل شیخ
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
Afaq Mansoor Khan
 

Similar to Algo>ADT list & linked list (20)

Lecture 3 List of Data Structures & Algorithms
Lecture 3 List of Data Structures & AlgorithmsLecture 3 List of Data Structures & Algorithms
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
Khuram Shahzad
 
Linked list
Linked list Linked list
Linked list
Arbind Mandal
 
Linked list.docx
Linked list.docxLinked list.docx
Linked list.docx
EmilyMengich
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
Amit Vats
 
LinkedList1LinkedList1LinkedList1111.pdf
LinkedList1LinkedList1LinkedList1111.pdfLinkedList1LinkedList1LinkedList1111.pdf
LinkedList1LinkedList1LinkedList1111.pdf
timoemin50
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
Durga Devi
 
DS Unit 2.ppt
DS Unit 2.pptDS Unit 2.ppt
DS Unit 2.ppt
JITTAYASHWANTHREDDY
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
ssuserd2f031
 
Linked List Representation of a Linked List.pptx
Linked List Representation of a Linked List.pptxLinked List Representation of a Linked List.pptx
Linked List Representation of a Linked List.pptx
AAUsH2
 
linkedlistforslideshare-210123143943.pptx
linkedlistforslideshare-210123143943.pptxlinkedlistforslideshare-210123143943.pptx
linkedlistforslideshare-210123143943.pptx
shesnasuneer
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
FaheemMahmood2
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
Sumathi Kv
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
Waf1231
 
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssssDSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
beshahashenafe20
 
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptxDSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
vaibhavkore8
 
Linked list and its operations - Traversal
Linked list and its operations - TraversalLinked list and its operations - Traversal
Linked list and its operations - Traversal
kasthurimukila
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data Structure
Muhazzab Chouhadry
 
Linked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operationsLinked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Lecture 3 List of Data Structures & Algorithms
Lecture 3 List of Data Structures & AlgorithmsLecture 3 List of Data Structures & Algorithms
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
Amit Vats
 
LinkedList1LinkedList1LinkedList1111.pdf
LinkedList1LinkedList1LinkedList1111.pdfLinkedList1LinkedList1LinkedList1111.pdf
LinkedList1LinkedList1LinkedList1111.pdf
timoemin50
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
Durga Devi
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
ssuserd2f031
 
Linked List Representation of a Linked List.pptx
Linked List Representation of a Linked List.pptxLinked List Representation of a Linked List.pptx
Linked List Representation of a Linked List.pptx
AAUsH2
 
linkedlistforslideshare-210123143943.pptx
linkedlistforslideshare-210123143943.pptxlinkedlistforslideshare-210123143943.pptx
linkedlistforslideshare-210123143943.pptx
shesnasuneer
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
Sumathi Kv
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
Waf1231
 
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssssDSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
DSA chapter 4.pptxhdjaaaaaadjhsssssssssssssssssssssssssss
beshahashenafe20
 
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptxDSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
vaibhavkore8
 
Linked list and its operations - Traversal
Linked list and its operations - TraversalLinked list and its operations - Traversal
Linked list and its operations - Traversal
kasthurimukila
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data Structure
Muhazzab Chouhadry
 
Linked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operationsLinked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Ad

More from Ain-ul-Moiz Khawaja (17)

Algo>Queues
Algo>QueuesAlgo>Queues
Algo>Queues
Ain-ul-Moiz Khawaja
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
Ain-ul-Moiz Khawaja
 
Algo>Stacks
Algo>StacksAlgo>Stacks
Algo>Stacks
Ain-ul-Moiz Khawaja
 
Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
Ain-ul-Moiz Khawaja
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
Ain-ul-Moiz Khawaja
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
Ain-ul-Moiz Khawaja
 
Algorithum Analysis
Algorithum AnalysisAlgorithum Analysis
Algorithum Analysis
Ain-ul-Moiz Khawaja
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Huffman > Data Structures & Algorithums
Huffman > Data Structures & AlgorithumsHuffman > Data Structures & Algorithums
Huffman > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Graphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & AlgorithumsGraphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Data Structures & Algorithms
Data Structures & AlgorithmsData Structures & Algorithms
Data Structures & Algorithms
Ain-ul-Moiz Khawaja
 
Turn over
Turn overTurn over
Turn over
Ain-ul-Moiz Khawaja
 
Attribution Theories
Attribution TheoriesAttribution Theories
Attribution Theories
Ain-ul-Moiz Khawaja
 
Attribution Theory
Attribution TheoryAttribution Theory
Attribution Theory
Ain-ul-Moiz Khawaja
 
Absenteeism
AbsenteeismAbsenteeism
Absenteeism
Ain-ul-Moiz Khawaja
 
HRM Employee Turnover
HRM Employee TurnoverHRM Employee Turnover
HRM Employee Turnover
Ain-ul-Moiz Khawaja
 
Ad

Recently uploaded (20)

Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
National Information Standards Organization (NISO)
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Debunking the Myths behind AI - v1, Carl Dalby
Debunking the Myths behind AI -  v1, Carl DalbyDebunking the Myths behind AI -  v1, Carl Dalby
Debunking the Myths behind AI - v1, Carl Dalby
Association for Project Management
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 

Algo>ADT list & linked list

  • 1. 1 List ADT & Linked Lists
  • 2. 2 List A Flexible structure, because can grow and shrink on demand. Elements can be:  Inserted  Accessed  Deleted At any position
  • 3. 3 List Lists can be:  Concatenated together.  Split into sublists. Mostly used in Applications like:  Information Retrieval  Programming language translation  Simulation
  • 4. 4 List A List is a sequence of zero or more elements of a given type (say elementtype) Represented by a comma-separated sequence of elements: a1, a2,…an Where, n >= 0 and each ai is of type elementtype.
  • 5. 5 List if n>= 1, a1 is the first element an is the last element if n = 0, we have an empty list
  • 6. 6 List The elements of a list can be linearly ordered. ⇒ai precedes ai+1 for i = 1,2,3…n-1 ai follows ai-1 for i = 2,3,4…n The element ai is at position i. END(L) will return the position following position n in an n-element list L. Position END(L) has a varying distance as the list grows and shrinks, all other positions have a fixed distance from the beginning of the list.
  • 7. 7 Common Operations on List ADT 1. INSERT(x,p,L): Insert x at position p in list L. If list L has no position p, the result is undefined. 2. LOCATE(x,L): Return the position of x on list L. 3. RETRIEVE(p,L): Return the element at position p on list L. 4. DELETE(p,L): Delete the element at position p on list L. 5. NEXT(p,L): Return the position following p on list L.
  • 8. 8 Common Operations on List ADT 6. PREVIOUS(p,L): Return the position preceding position p on list L. 7. MAKENULL(L): Causes L to become an empty list and returns position END(L). 8. FIRST(L): Returns the first position on the list L. 9. PRINTLIST(L): Print the elements of L in order of occurrence.
  • 9. 9 Implement a Linked Structure Using an Array 1 3 4 10 I data[I] next[I] 0 3 6 1 * * 2 1 0 3 10 -1 4 * * 5 * * 6 4 3 Need a start link. start end How to insert, delete, and append?
  • 10. 10 Linked Structure Using an Array With a free list 1 3 4 10 I data[I] next[I] 0 3 6 1 * 4 2 1 0 3 10 -1 4 * -1 5 * 1 6 4 3 Data_start end Free list Free_start
  • 11. 11 Linked Structure Using an Array I data[I] next[I] 0 * 6 1 * 4 2 * 0 3 * 5 4 * -1 5 * 1 6 * 3 Free_start end Free list
  • 12. 12 Linked Lists Pointer Based Implementation of Linked List ADT Dynamically allocated data structures can be linked together to form a chain. A linked list is a series of connected nodes (or links) where each node is a data structure. A linked list can grow or shrink in size as the program runs. This is possible because the nodes in a linked list are dynamically allocated.
  • 13. 13 If new information needs to be added to the list, the program - a) Allocates another node b) Inserts it into the series. If a piece of information is to be deleted from the list, the program - a) Deletes the node containing the information Advantages of Linked Lists over Arrays Linked lists are more complex to code and manage than arrays, but they have some distinct advantages. a) A linked list can easily grow and shrink in size.
  • 14. 14 (The programmer doesn’t need to know how many nodes will be in the list. They are created in memory as needed). b) Speed of insertion or deletion from the list. e.g. with an array, to insert an element, requires all elements beyond the insertion point to be moved forward one position to make room for the new element. Similarly, to delete an element, requires all elements after the insertion point to be moved back one position to close the gap. When a node is inserted, or deleted from a linked list, none of the other nodes have to be moved!!!!
  • 15. 15 Composition of a Linked List Each node in the linked list contains - a) One or more members that represent data (e.g. inventory records, customer names, addresses, telephone numbers, etc). b) A pointer, that can point to another node. Data Members Pointer
  • 16. 16 A linked list is called “linked” because each node in the series (i.e. the chain) has a pointer to the next node in the list, e.g. List Head NULL a) The list head is a pointer to the first node in the list. b) Each node in the list points to the next node in the list. c) The last node points to NULL (the usual way to signify the end). Note, the nodes in a linked list can be spread out over the memory.
  • 17. 17 Declarations How to declare a linked list in C++? Step 1) Declare a data structure for the nodes. e.g. the following struct could be used to create a list where each node holds a float - struct ListNode { float value; ListNode *next; };
  • 18. 18 a) The first member of the ListNode struct is a float called value. It is to hold the node’s data. b) The second member is a pointer called next. It is to hold the address of any object that is a ListNode struct. Hence each ListNode struct can point to the next one in the list. The ListNode struct contains a pointer to an object of the same type as that being declared. It is called a self-referential data structure. This makes it possible to create nodes that point to other nodes of the same type.
  • 19. 19 Step 2) Declare a pointer to serve as the list head, e.g ListNode *head; Before you use the head pointer, make sure it is initialized to NULL, so that it marks the end of the list. Once you have done these 2 steps (i.e. declared a node data structure, and created a NULL head pointer, you have an empty linked list. The next thing is to implement operations with the list. Linked List Operations There are 5 basic linked list operations -
  • 20. 20 1) Appending a node 2) Traversing a list 3) Inserting a node 4) Deleting a node 5) Destroying the list We will implement this Linked List ADT (abstract data type) that performs basic linked list operations using the ListNode structure and head pointer declared earlier. We use the following class declaration - class FloatList { private: // Declare a structure for the list struct ListNode { float value; struct ListNode *next; }; ListNode *head; // List head pointer
  • 21. 21 public: FloatList(void) // Constructor { head = NULL; } ~FloatList(void); // Destructor void appendNode(float); void insertNode(float); void deleteNode(float); void displayList(void); }; Note, the constructor initializes the head pointer to NULL, establishing an empty linked list. The class has members to append, insert, delete and display (all) nodes. The destructor destroys the list by deleting all its nodes.
  • 22. 22 We now examine these functions individually - 1) Appending a Node to the List To append a node to a linked list, means adding it to the end of the list. The appendNode member function accepts a float argument, num. The function will - a) allocate a new ListNode structure b) store the value in num in the node’s value member c) append the node to the end of the list This can be represented in pseudo code as follows-
  • 23. 23 a) Create a new node. b) Store data in the new node. c) If there are no nodes in the list Make the new node the first node. Else Traverse the List to Find the last node. Add the new node to the end of the list. End If. The actual C++ code for the above pseudo code is -
  • 24. 24 void FloatList::appendNode(float num) { ListNode *newNode, *nodePtr; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; // If there are no nodes in the list // make newNode the first node if (!head) head = newNode; else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } }
  • 25. 25 We examine this important piece of code in detail. The function declares the following local variables - ListNode *newNode, *nodePtr; a) The newNode pointer will be used to allocate and point to the new node. b) The nodePtr pointer will be used to travel down the linked list, looking for the last node. The next few statements - i) create a new node ii) store num in its value member.
  • 26. 26 newNode = new ListNode; newNode->value = num; newNode->next = NULL; The last statement above is important. This node will become the last node in the list, so its next pointer must point to NULL. Now test the head pointer to see if there are any nodes already in the list. If head points to NULL, we make the new node the first in the list. Do this by making head point to the new node, i.e. if(!head) head = newNode;
  • 27. 27 But, if head does not point to NULL, then there must already be nodes in the list. The else part must then contain code to - a) Find the end of the list b) Insert the new node. else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; }
  • 28. 28 The code uses nodePtr to travel down the list. It does this by assigning nodePtr to head. nodePtr = head; A while loop is then used to traverse (i.e. travel through) the list, looking for the last node (that will have its next member pointing to NULL). while(nodePtr->next) nodePtr = nodePtr->next; Now the nodePtr is pointing to the last node in the list, so make its next member point to newNode. nodePtr->next = newNode;
  • 29. 29 This appends newNode at the end of the list. Remember, newNode->next already points to NULL. // This program demonstrates a simple append // operation on a linked list. #include <iostream.h> #include "FloatList.h” void main(void) { FloatList list; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); } (This program displays no output.)
  • 30. 30 We step through the above program, observing how the appendNode function builds a linked list to store the 3 argument values. The head pointer is automatically initialized to 0 (NULL), indicating the list is empty. The first call to appendNode passes 2.5 as the argument. A new node is allocated in memory. 2.5 is copied into its value member, and NULL is assigned to its next pointer.
  • 31. 31 newNode = new ListNode; newNode->value = num; newNode->next = NULL; The next statement to execute is the following if statement. if (!head) head = newNode; There are no more statements to execute, so control returns to function main. Since head points to NULL, then the condition !head is true, so the statement, head = newNode is executed, making newNode the first node in the list.
  • 32. 32 There are no more statements to execute, so control returns to the function main. In the second call to appendNode, 7.9 is passed as the argument. Again, the first 3 statements create a new node, which stores the argument in the node’s value member, and assigns its next pointer to NULL. Visually this is -
  • 33. 33 Since head no longer points to NULL, the else part of the if statement is executed. else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } The first statement in the else block assigns the value in head to nodePtr. So, nodePtr and head point to the same node.
  • 34. 34 Look now at the next member of the node that nodePtr points at. Its value is NULL, so nodePtr->next also points to NULL. So, nodePtr is already at the end of the list, so the while loop terminates. The last statement, nodePtr->next = newNode, causes nodePtr->next to point to the new node. This appends newNode to the end of the list, as shown -
  • 35. 35 The third time appendNode is called, 12.6 is passed as argument. Again, the first 3 statements create a node with the argument stored in the value member. Now, the else part of the if statement executes. Again nodePtr is made to point to the same node as head.
  • 36. 36 Since nodePtr->next is not NULL, the while loop will execute. After its first iteration, nodePtr will point to the second node in the list. The while loop’s conditional test will fail after the first iteration because nodePtr->next now points to NULL. The last statement nodePtr->next = newNode causes nodePtr->next to point to the new node. This appends newNode to the end of the list, as shown -
  • 37. 37 The above is the final state of the linked list. 2) Traversing a Linked List The previous function appendNode, used a while loop that traverses, or travels through the linked list. We now demonstrate the displayList member function, that traverses the list, displaying the value member of each node.
  • 38. 38 The following pseudocode represents the algorithm - Assign list head to node pointer While node pointer is not NULL Display the value member of the node pointed to by node pointer. Assign node pointer to its own next member. End While. The actual C++ code is -
  • 39. 39 void FloatList::displayList(void) { ListNode *nodePtr; nodePtr = head; while(nodePtr) { cout << nodePtr->value << endl; nodePtr = nodePtr->next; } }
  • 40. 40 // This program calls the displayList member function. // The funcion traverses the linked list displaying // the value stored in each node. #include <iostream.h> #include "FloatList.h" void main(void) { FloatList List; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); list.displayList(); } Program 17-2 Output 2.5 7.9 12.6
  • 41. 41 Usually, when an operation is performed on some or all of the nodes in a linked list, a traversal algorithm is used. We will see variations of this traversal algorithm used throughout this chapter. 3) Inserting a Node Inserting a node in the middle of a list is more complicated than appending a node. Assume all values in the list are sorted, and you want all new values to be inserted in their proper position (preserving the order of the list). We use the same ListNode structure again, with pseudo code.
  • 42. 42 This pseudocode shows the algorithm to find the new node’s proper position in the list, and inserting it there. It is assumed the nodes already in the list are ordered. Create a new node. Store data in the new node. If there are no nodes in the list Make the new node the first node. Else Find the first node whose value is greater than or equal the new value, or the end of the list (whichever is first). Insert the new node before the found node, or at the end of the list if no node was found. End If.
  • 43. 43 The code for the traversal algorithm is shown below. (As before, num holds the value being inserted into the list.) // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is less // than num. while (nodePtr != NULL && nodePtr->value < num) { previousNode = nodePtr; nodePtr = nodePtr->next; } The entire insertNode function begins on the next slide.
  • 44. 44 The new algorithm finds the first node whose value is greater than or equal to the new value. The new node is then inserted before the found node. This requires two pointers during the traversal - a) One to point to the node being inspected b) The other to point to the previous node. The code above shows this traversal algorithm. Num holds the value being inserted into the list.
  • 45. 45 void FloatList::insertNode(float num) { ListNode *newNode, *nodePtr, *previousNode; // Allocate a new node & store Num newNode = new ListNode; newNode->value = num; // If there are no nodes in the list // make newNode the first node if (!head) { head = newNode; newNode->next = NULL; } else // Otherwise, insert newNode. { // Initialize nodePtr to head of list nodePtr = head; The code below uses the pointers nodePtr and previousNode. previousNode always points to the node before the one pointed to by nodePtr. The entire insertNode function is shown below.
  • 46. 46 // Skip all nodes whose value member is less // than num. while (nodePtr != NULL && nodePtr->value < num) { previousNode = nodePtr; } nodePtr = nodePtr->next; // If the new mode is to be the 1st in the list, // insert it before all other nodes. if (previousNode == NULL) { head = newNode; newNode->next = nodePtr; } else { previousNode->next = newNode; newNode->next = nodePtr; } } }
  • 47. 47 // This program calls the displayList member function. // The function traverses the linked list displaying // the value stored in each node. #include <iostream.h> #include "FloatList.h” void main(void) { FloatList list; // Build the list list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); // Insert a node in the middle // of the list. list.insertNode(10.5); // Dispay the list list.displayList(); }
  • 48. 48 Program Output 2.5 7.9 10.5 12.6 As in previous program, this program calls the appendNode function 3 times to build the list with the values 2.5, 7.9, 12.6 The insertNode function is called with argument 10.5 In insertNode, the new node is created, and the function argument is copied to its value member.
  • 49. 49 Since the list already has nodes stored in it, the else part of the if statement will execute. It begins by assigning nodePtr to Head, i.e. Since nodePtr is not NULL, and nodePtr->value is less than num, the while loop will iterate. During the iteration, previousNode is made to point to the node that nodePtr is pointing to. nodePtr is then advanced to point to the next node. i.e.
  • 50. 50 The loop does its test once more. Since nodePtr is not NULL, and nodePtr->value is less than num, the loop iterates a second time. During the second iteration, both previousNode and nodePtr are advanced by one node in the list, i.e.
  • 51. 51 This time, the loop’s test will fail, because nodePtr is not less than num. The statements after the loop will execute, which cause previousNode->next to point to newNode, and newNode->next to point to nodePtr, i.e.
  • 52. 52 This leaves the list in its final state. The nodes (you will see if you follow the links from the head pointer to NULL) are stored in the order of their value members. Deleting a Node This requires 2 steps - a) Remove the node from the list without breaking the links created by the next pointers. b) Delete the node from memory.
  • 53. 53 The deleteNode member function searches for a node with a particular value and deletes it from the list. It uses an agorithm similar to the insertNode function. The two node pointers nodePtr and previousPtr are used to traverse the list (as before). When nodePtr points to the node to be deleted, previousNode->next is made to point to nodePtr->next. This removes the node pointed to by nodePtr from the list. The final step is to free the memory used by the node using the delete operator.
  • 54. 54 void FloatList::deleteNode(float num) { ListNode *nodePtr, *previousNode; // If the list is empty, do nothing. if (!head) return; // Determine if the first node is the one. if (head->value == num) { nodePtr = head->next; delete head; head = nodePtr; } else { // Initialize nodePtr to head of list nodePtr = head;
  • 55. 55 // Skip all nodes whose value member is // not equal to num. while (nodePtr != NULL && nodePtr->value != num) { previousNode = nodePtr; nodePtr = nodePtr->next; } // Link the previous node to the node after // nodePtr, then delete nodePtr. previousNode->next = nodePtr->next; delete nodePtr; } } // This program demonstrates the deleteNode member function #include <iostream.h> #include "FloatList.h“ void main(void) { FloatList list;
  • 56. 56 // Build the list list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); cout << "Here are the initial values:n"; list.displayList(); cout << endl; cout << "Now deleting the node in the middle.n"; cout << "Here are the nodes left.n"; list.deleteNode(7.9); list.displayList(); cout << endl; cout << "Now deleting the last node.n"; cout << "Here are the nodes left.n"; list.deleteNode(12.6); list.displayList(); cout << endl; cout << "Now deleting the only remaining node.n"; cout << "Here are the nodes left.n"; list.deleteNode(2.5); list.displayList(); }
  • 57. 57 Program Output Here are the initial values: 2.5 7.9 12.6 Now deleting the node in the middle. Here are the nodes left. 2.5 12.6 Now deleting the last node. Here are the nodes left. 2.5 Now deleting the only remaining node. Here are the nodes left.
  • 58. 58 To show how deleteNode works, we do a step through of the call to delete the node with value 7.9 Look at the else part of the 2nd if statement. It is here the function does its thing, since the list is not empty, and the first node does not contain 7.9 The node pointers nodePtr and previousPtr are used to traverse the list (as with the insertNode function). The while loop terminates when the value 7.9 is found. When this happens the list and other pointers are in the following state -
  • 59. 59 Then the following statement executes - previousNode->next = nodePtr->next; This causes the links in the list to bypass the node that nodePtr points to. The node still exists in memory, but it is removed from the list.
  • 60. 60 The bypassed node is destroyed with the statement delete nodePtr; Destroying the List Use the class’s destructor to release all the memory used by the list. It does this by stepping through the list, deleting each node, one by one.
  • 61. 61 FloatList::~FloatList(void) { ListNode *nodePtr, *nextNode; nodePtr = head; while (nodePtr != NULL) { nextNode = nodePtr->next; delete nodePtr; nodePtr = nextNode; } } Note the use of nextNode instead of previousNode. The nextNode pointer is used to hold the position of the next node in the list, so it will be available after the node pointed to by nodePtr is deleted.