DSA Chapter 3
DSA Chapter 3
Linked List
1
Lists - Introduction
• A list is a fundamental data structure that stores
and manage a collection of elements in a specific
order or sequential order.
• we can access the elements by their position or
index within the list.
• It can be implemented in various ways, such as
arrays or linked lists.
2
Lists – Definition
• Arrays: Lists implemented as arrays allocate memory in
contiguous(adjacent) blocks, allowing random access to
elements using indices.
• Linked Lists: Lists implemented as linked lists consist of
nodes where each node contains the data and a reference
to the next node.
Types of Data Structures to implement list
• There are two broad types of data structure based on
their memory allocation:
– Static Data Structures
– Dynamic Data Structures
3
I. Static Data Structures
• Are data structures that are defined & allocated before
execution, thus the size cannot be changed during time of
execution.
Example: Array implementation
II. Dynamic Data Structure
• Are data structure that can grow and shrink in size and
also permits discarding of unwanted memory during
execution time.
Example: Linked list implementation
4
Array-Based List implementation
• There are two standard approaches to implementing lists, the
array-based list and the linked list.
• Array-Based List Insert:
– Insert items up/down.
8
Example :
struct student {
char name[20];
int age;
char Dept[20];
};
9
Accessing Members of Structure Variables
•The Dot operator (.): to access data members of
structure variables.
•The Arrow operator (->): to access data members of
pointer variables pointing to the structure.
Example:
struct student stud;
struct student *studptr;
cout<<stud.name;
OR
cout<<studptr->name;
10
Self-Referential Structures
• Structures can hold pointers to instances of themselves.
• Structure can hold a location to another instance of itself.
This helps in creating relationships between different
instances of the same structure,
• Example:
struct student{
char name[20];
int age;
char Dept[20];
struct student *next;
};
11
What is Pointer?
• A pointer is a variable that stores (holds) the memory
address of another variable.
• Pointer is allows you to indirectly manipulate data by
referring to the location in memory where the actual data
is stored.
• Syntax
data_type *pointer_name;
• We can get address of variable using ampersand (&).
• To obtain the value stored at the location is known as
dereferencing(*) the pointer
12
Linked List-Based List implementation
• The second approach for implementing lists makes use of
structure and pointers and is called a linked list.
What is Linked List?
• It is a linear data structure that includes a series of
connected nodes.
• The linked list uses dynamic memory allocation,
– i.e. it allocates memory for new list elements as needed.
• It is self-referential structure.
13
Linked List-Based List implementation
• A node in the linked list contains two parts,
– i.e., first is the data part and second is the address part.
– The data field holds the actual elements on the list.
– The address (pointer) field contains the address of the next
node in the list.
14
Linked List-Based List implementation
16
Why use linked list over array?
• Linked list is useful because –
17
Advantages of Linked list
• The advantages of using the Linked list are given as
follows -
– Insertion and deletion - Unlike arrays, insertion, and
deletion in linked list is easier.
• Array elements are stored in the consecutive location, whereas
the elements in the linked list are stored at a random location.
• To insert or delete an element in an array, we have to shift the
elements for creating the space. Whereas, in linked list,
instead of shifting, we just have to update the address of the
pointer of the node.
18
Disadvantages of Linked list
• The limitations of using the Linked list are given as
follows -
– Memory usage - In linked list, node occupies more memory
than array. Each node of the linked list occupies two types
of variables, i.e., one is a simple variable, and another one is
the pointer variable.
– Traversal - Traversal is not easy in the linked list. If we have
to access an element in the linked list, we cannot access it
randomly, while in case of array we can randomly access it
by index. For example, if we want to access the 3rd node,
then we need to traverse all the nodes before it. So, the time
required to access a particular node is large.
– Reverse traversing - Backtracking or reverse traversing is
difficult in a linked list.
19
Applications of Linked list
The applications of the Linked list are given as follows –
Dynamic Memory Allocation
Implementation of Data Structures
Operating Systems
Music Players
Networking
Undo Functionality
Job Schedulers
20
Operations performed on Linked list (1)
The basic operations that are supported by a list are
mentioned as follows –
• Creation – Creating or defining a linked list.
• Insertion - This operation is performed to add an element
into the linked list..
• Deletion - It is performed to delete an operation from the
linked list..
• Display - It is performed to display the elements of the
linked list..
• Search - It is performed to search an element from the
linked list using the given key.
• Traversal: Accessing and visiting each node in the linked list
to perform operations like printing elements or performing
computations on them. 21
Operations performed on Linked list(2)
• Concatenation/Merging: Combining two linked lists to
create a single linked list.
• Reversal: Changing the direction of the linked list, where the
last node becomes the first and vice versa.
• Sorting: Rearranging the elements in ascending or
descending order within the linked list.
• Splitting: Dividing a linked list into two or more smaller
linked lists based on a certain condition or position.
• Size/Length: Determining the number of nodes or elements
in the linked list.
22
Types of linked Lists
There are Three basic types of linked list
1. Singly Linked list
singly linked list is a type of data structure where each
element (node) holds a value and a reference (or
pointer) to the next node in the sequence.
starts from a head node and each node points to the
next node, forming a linear sequence. The last node
typically points to a null value, indicating the end of
the list.
23
Types of linked Lists
There are Three basic types of linked list
2. Doubly linked list
24
Types of linked Lists
Circular Linked List:
25
Singly Linked List
Diagram Representation
a b c d
27
How to declare a Singly linked list?
• We can declare the linked list by using the user-
defined data type structure and pointer.
struct node
{
int data;
struct node *next;
}
29
Example
30
Defining(Creating) the data structure for
linked lists
struct node
{
int id;
struct student *next;
};
struct node *start = NULL;
31
Inserting a node in a SLL
• First we declare pointer item and assign a pointer (*p) to it.
Then create node using the new statement as follow
struct node
{
int id[20];
struct student *next;
};
struct node *start = NULL;
struct node *temp;
temp = new node ;
32
Inserting a node in a SLL
• Having declared the node, we ask the user to fill id.
cout<<“Enter your id:\n”;
cin>>temp->id;
temp->next= NULL
33
Insertion at the Beginning:
To insert a node at the beginning of a singly linked list,
follow these steps:
Create a new node with the data to be inserted.
Set the 'next' pointer of the new node to point to the
current head of the list.
Update the head pointer to point to the new node.
34
void insert_beg()
{
.
.
.
.
.
.
.
.
.
.
}
35
Insertion at the End:
Inserting a node at the end of the list involves traversing the
list until the last node and then appending the new node.
Create a new node with the data to be inserted.
Traverse the list to reach the last node.
Set the 'next' pointer of the last node to point to the new
node.
Set the 'next' pointer of the new node to NULL (indicating
it's now the last node).
36
void insert_end()
{
.
.
.
.
.
.
.
.
.
.
.
}
37
Insertion at a Specific Position:
Inserting a node at a specific position involves traversing
the list up to the desired position and adjusting pointers to
insert the new node.
Create a new node with the data to be inserted.
Traverse the list up to the position before the desired
insertion point.
Adjust pointers to insert the new node at the desired
position.
38
void insert_after()
{
.
.
.
.
.
.
.
39
Displaying the list of nodes
• Having added one or more nodes, we need to display the list of
nodes on the screen using the following steps
Steps
1. Set a temporary pointer to point to the same thing as the start
pointer
2. If the pointer points to NULL, display the message “End of list”
and stop.
3. Otherwise, display the details of the node pointed by the start
node
4. Make the temporary pointer point to the same thing as the next
pointer of the node it is currently indicating
5. Jump back to step 2
40
void display()
{
.
.
.
.
.
.
.
.
.
}
41
Deleting a node in SLL
Here also we have three cases:-
– Deleting the first node
• It involves deletion of a node from the beginning of the list.
This is the simplest operation among all. It just need a few
adjustments in the node pointers.
– Deleting the last node
• It involves deleting the last node of the list. The list can
either be empty or full. Different logic is implemented for
the different scenarios.
– Deleting after a specified node
• It involves deleting the node after the specified node in the
list. we need to skip the desired number of nodes to reach
the node after which the node will be deleted. This requires
traversing through the list.
42
Deleting the first node
Here we apply 2 steps:-
– Making the start pointer point towards the 2nd
node.
– Deleting the first node using delete keyword.
start
43
void del_first(){
if(start==NULL)
cout<<”\n Error……List is empty\n”;
else
{
student * temp=start;
start=temp->next;
delete temp;
cout<<”\n First node deleted!”;
}
}
44
Deleting the last node
Here we apply 2 steps:-
Making the second last node’s next pointer point to NULL
Deleting the last node via delete keyword
start
45
void del_last()
{
if(start==NULL)
cout<<”\n Error….List is empty”;
else
{
student *q=start;
while(q->next->next!=NULL)
q=q->next;
student *temp=q->next;
q->next=NULL;
delete temp;
cout<<”\n Deleted successfully…”;
}
}
46
Deleting a particular node
• Here we make the next pointer of the node previous to the
node being deleted, point to the successor node of the node
to be deleted and then delete the node using delete keyword.
To be deleted
47
void del(int c)
{
node *q=start;
for(int i=1;i<c; i++)
{
q=q->next;
if(q==NULL)
cout<<”\n Node not found\n”;
}
if(i==c)
{
node *p=q->next; //node to be deleted
q->next=p->next;//disconnecting the node p
delete p;
cout<<“Deleted Successfully”;
}
}
48
Navigating/Traversing through the list
To Move Forward:
1. Set a pointer to point to the same thing as the
start pointer.
2. If the pointer points to NULL, display the
message “list is empty" and stop.
3. Otherwise, move to the next node by making
the pointer point to the same thing as the next
pointer of the node it is currently
indicating(using current pointer).
49
Navigating/Traversing through the list
To Move to Backward: (single linked list)
1. Set a pointer to point to the same thing as the
start pointer.
2. If the pointer points to NULL, display the
message “list is empty" and stop.
3. Set a new pointer(previous) and assign the same
value as start pointer and move forward until you
find the node before the one we are considering at
the moment(using current pointer).
4. Set current pointer equal to the new pointer
(previous pointer)
50
Arrays Vs Linked Lists
Arrays Linked list
53
Doubly linked lists
• A sample node in a doubly linked list is shown in the
figure.
54
Doubly linked lists
• Advantage: given a node,
• It is easy to visit its predecessor (previous) node.
• It is convenient to traverse linked lists Forwards and Backwards.
A B C
Head (Start)
55
Doubly linked lists
Here, there is no pointer to the start of the list, there is simply a pointer
to some position in the list that can be moved left or right.
56
DLL’s compared to SLL’s
Advantages: Disadvantages:
Can be traversed in Requires more space.
either direction (may be List manipulations are
essential for some slower (because more
programs). links must be changed).
Some operations, such Greater chance of
as deletion and inserting having bugs (because
before a node, become more links must be
easier. manipulated).
57
Structure of DLL
struct student
{
char name[20];
int age;
struct node *next;
struct node *previous;//holds the address of previous node
};
Previous .Data .Next
58
Inserting at the beginning
59
void insert_beg()
{
60
Inserting at the end of the list
61
void insert_end()
{
} 62
Inserting after a specified node
}
64
Navigating through DDL
To Move to Backward:
1. Set a pointer to point to the same thing as the start
pointer.
2. If the pointer points to NULL, display the message
“list is empty" and stop.
3. Otherwise, move back to the previous node by
making the pointer point to the same thing as the
previous pointer of the node it is currently
indicating.
65
Deleting a node
• Node deletion from a DLL involves changing two links
• In this example, we will delete node b
myDLL
a b c
66
void del_begun()
{
67
Variations of Linked Lists
• Circular linked lists
The last node points to the first node of the list.
A B C
Start
How do we know when we have finished traversing
the list?
(Hint: check if the pointer of the current node is
equal to the Start (head) pointer).
68
Exercises
1. Write a C++ program using single and double linked list
data structure that keeps track of student record. Each
student has Name, ID, Age, and Department. The
program should include the following operations.
a) Add a new student data from the keyboard(front,
middle, last)
b) Delete a node ( the first, last, middle)
c) Display the whole list of students
d) Search a specific node
69