0% found this document useful (0 votes)
19 views

DSA Chapter 3

The document discusses linked lists as a data structure. It defines linked lists and compares them to array-based implementations. It describes the components of linked lists including nodes and pointers. It also covers operations like insertion, deletion, traversal and applications of linked lists.

Uploaded by

F&B House
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

DSA Chapter 3

The document discusses linked lists as a data structure. It defines linked lists and compares them to array-based implementations. It describes the components of linked lists including nodes and pointers. It also covers operations like insertion, deletion, traversal and applications of linked lists.

Uploaded by

F&B House
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

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.

• Inserting an element at the head of an array-based list requires


shifting all existing elements in the array by one position toward
the tail. 5
Array-Based List Class (1)
#include <iostream>
Using namespace std;
const int MAX_SIZE = 7;
int arr[MAX_SIZE];
int length = 0;
void insert(int element) {
if (length < MAX_SIZE) {
arr[length] = element;
length++; }
else {
cout<<"List is full. Cannot append more elements." <<endl;
}}
void get(int index) {
if (index >= 0 && index < length) {
cout<<“Element: “<< arr[index];}
else {
cout << "Index out of bounds." <<endl;
}}
Array-Based List Class (2)
void display() {
cout << "Elements in the list: ";
for (int i = 0; i < length; i++) {
cout << arr[i] << " ";
}
cout<<endl; }
int main()
{
insert(5);
insert(10);
insert(15);
insert(8);
get(1);
return 0;
}
Revision to Structure
• Structure is a user – defined data type that allows you to
combine different data type together.
• It helps in organizing related data items under one/single name
• The data item of structure is called member of the structure.
Declaration of structure
• Structure is defined using the struct keyword.
struct name {
data type1 member 1;
data type2 member 2
.
data type n member n;
};

8
Example :
struct student {
char name[20];
int age;
char Dept[20];
};

• The struct keyword creates a new user defined data


type.

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.

• The last node of the list contains a pointer to the null.

14
Linked List-Based List implementation

• Start (Head): Special pointer that points to the first


node of a linked list, so that we can keep track of the
linked list.
• The last node should point to NULL to show that it
is the last link in the linked list.
15
Why use linked list over array?
• Now, the question arises why we should use linked list
over array?
• Linked list is a data structure that overcomes the
limitations of arrays.
• Limitations of arrays –
– The size of the array must be known in advance before
using it in the program.
– It is almost impossible to expand the size of the array at run
time.
– Inserting an element in the array needs shifting of all.

16
Why use linked list over array?
• Linked list is useful because –

– Dynamic data structure - The size of the linked list may


vary according to the requirements. Linked list does not
have a fixed size. So size is no longer a problem

– Memory efficient - The size of a linked list can grow or


shrink according to the requirements, so memory
consumption in linked list is efficient.

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

Here is a singly-linked list (SLL):


start

a b c d

• Each node contains a value(data) and a pointer to the


next node in the list.
• Start is the header pointer which points at the first
node in the list. 26
Example

• This linked list has four nodes in it, each with a


link to the next node in the series (in the linked
list).

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;
}

we have defined a structure named as


node that contains two variables, one
is data that is of integer type, and
another one is next that is a pointer
which contains the address of next
node.
28
Linked Lists: Some Properties
• Head stores address of first node
• Info stores information
• Link stores address of next node
– Assume info type int

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

one two three

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

node1 node2 node3

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.

node1 node2 node3

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

Fixed size: Resizing is expensive Dynamic size


Insertions and Deletions are inefficient: Insertions and Deletions are efficient:
Elements are usually shifted No shifting

Random access i.e., efficient indexing No random access


 Not suitable for operations requiring
accessing elements by index such as
sorting
No memory waste if the array is full or Since memory is allocated
almost full; otherwise may result in dynamically(acc. to our need) there is no
much memory waste. waste of memory.

Sequential access is faster [Reason: Sequential access is slow [Reason:


Elements in contiguous memory Elements not in contiguous memory
locations] locations]
51
COMPLEXITY OF VARIOUS OPERATIONS IN
ARRAYS AND SLL
Operation ID-Array Complexity Singly-linked list Complexity
Insert at beginning O(n) O(1)
Insert at end O(1) O(1) if the list has tail
reference
O(n) if the list has no tail
reference
Insert at middle O(n) O(n)
Delete at beginning O(n) O(1)
Delete at end O(1) O(n)
Delete at middle O(n): O(1) access O(n): O(n) search, followed by
followed by O(n) shift O(1) delete
Search O(n) linear search O(n)
O(log n) Binary search
Indexing: What is the O(1) O(n)
element at a given
position k? 52
Doubly linked lists
• Each node points not only to Successor node (Next node),
but also to Predecessor node (Previous node).
• There are two NULL: at the first and last nodes in the
linked list.
• Therefore, in a doubly linked list, a node consists of three
parts:
• node data
• pointer to the next node in sequence (next pointer)
• pointer to the previous node (previous pointer)

53
Doubly linked lists
• A sample node in a doubly linked list is shown in the
figure.

• A doubly linked list containing three nodes having


numbers from 1 to 3 in their data part, is shown in the
following image.

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)

• It is not necessary to have start pointer, we can have any


pointer(current) pointing to one of the node in the list

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.

The reason we needed a start pointer in the ordinary linked list is


because, having moved on from one node to another, we can’t easily
move back, so without the start pointer, we would lose track of all the
nodes in the list that we have already passed. With the doubly linked
list, we can move the current pointer backwards and forwards at will.

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

Making next and previous pointer of the node to be


inserted point accordingly

Adjusting the next and previous pointers of the


nodes b/w which the new node accordingly 63
void insert_after()
{

}
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

• Deletion of the first node or the last node is a special


case

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

You might also like