SlideShare a Scribd company logo
1 of 58
Download to read offline
Linked List in Data
Structure
By
Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)*
Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra
http://www.simplycs.in http://www.sitcoe.org.in
Linked List
 Like arrays, Linked List is a linear data structure. Unlike arrays, linked list
elements are not stored at contiguous location; the elements are linked using
pointers.
 Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have
following limitations.
1) The size of the arrays is fixed: So we must know the upper limit on the
number of elements in advance. Also, generally, the allocated memory is equal
to the upper limit irrespective of the usage.
2) Inserting a new element in an array of elements is expensive, because room
has to be created for the new elements and to create room existing elements
have to shifted.
2
http://www.simplycs.in http://www.sitcoe.org.in
 For example, in a system if we maintain a sorted list of IDs in an
array id[].
 id[] = [1000, 1010, 1050, 2000, 2040].
 And if we want to insert a new ID 1005, then to maintain the
sorted order, we have to move all the elements after 1000
(excluding 1000).
Deletion is also expensive with arrays until unless some special
techniques are used.
 For example, to delete 1010 in id[], everything after 1010 has to
be moved.
3
http://www.simplycs.in http://www.sitcoe.org.in
 Advantages Linked List over arrays
1) Dynamic size
2) Ease of insertion/deletion
 Drawbacks of Linked List:
1) Random access is not allowed. We have to access elements
sequentially starting from the first node. So we cannot do
binary search with linked lists.
2) Extra memory space for a pointer is required with each
element of the list.
4
http://www.simplycs.in http://www.sitcoe.org.in
Representation of Linked List in C:
 A linked list is represented by a pointer to the first node of the linked list.
 The first node is called head. If the linked list is empty, then value of
head is NULL.
 Each node in a list consists of at least two parts:
1) data
2) pointer to the next node
 In C, we can represent a node using structures. Below is an example of
a linked list node with an integer data.
 In C#/Java, LinkedList can be represented as a class and a Node as a
separate class. The LinkedList class contains a reference of Node class
type.
 Write C Program to Create Linked List.
Data Address of Next Node
Data Data DataAddress of Next Node Address of Next Node Address of Next Node
40 2000 50 3000 60 NULL
0x1000 0x2000 0x3000 Address of Last Node is NULLAddress of
Head Node
5
Implementation of Linked List –
 Structure is used to define a node.
 Node is Collection of Data and Address to Next Node.
 Address of Next Node can be Stored in pointer type variable.
 Ex.
typedef struct node
{
int data;
struct node *next;
}node;
 It is Self Referential Structure in C.
 It is Assumed that, type of data stored in each node is of integer type.
 In C Programming, Memory can be acquired through use of standard library
functions malloc() and calloc() from stdlib.h header file.
 To Free Memory aquired, free(address) function is used.
Memory Allocation for node using malloc()
Function-
node *p;
p=(node *)malloc(sizeof(node));
p->data=40;
p->next=NULL; 40 NULL
p
data Next address
6
http://www.simplycs.in http://www.sitcoe.org.in
#include<stdio.h>
#include<stdlib.h> //calloc/malloc/free
struct Node
{
int data;
struct Node *next;
};
// Program to create a simple linked
// list with 3 nodes
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; //assign data in first node
head->next = second; // Link first node with the second node
/* data has been assigned to data part of first block (block
pointed by head). And next pointer of first block points
to
second. So they both are linked.
head second third
| | |
| | |
+---+---+ +----+----+ +-----+----+
| 1 | o----->| # | # | | # | # |
+---+---+ +----+----+ +-----+----+
*/
second->data = 2; //assign data to second node
second->next = third; // Link second node with the third
node
third->data = 3; //assign data to third node
third->next = NULL;
return 0;
}
// A simple C program to introduce a linked list
7
http://www.simplycs.in http://www.sitcoe.org.in
Types of Linked List
There are three common types of Linked List.
 Singly Linked List
 Doubly Linked List
 Circular Linked List
Singly Linked List
 It is the most common. Each node has data and a pointer to the next node.
typedef struct node
{
int data;
struct node *next;
}node;
Node Representation
in singly Linked List
8
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
 We add a pointer to the previous node in a doubly linked list. Thus,
we can go in either direction: forward or backward.
typedef struct node
{
int data;
struct node *next;
struct node *prev;
}node;
Node Representation
in doubly Linked List
9
http://www.simplycs.in http://www.sitcoe.org.in
Circular Linked List
 A circular linked list is a variation of linked list in which the last element is linked to
the first element. This forms a circular loop.
A circular linked list can be either singly linked or doubly linked.
 for Circular singly linked list, next pointer of last item points to the first item
 In Circular doubly linked list, prev pointer of first item points to last item as well.
typedef struct node
{
int data;
struct node *next;
}node;
Node Representation
in Circular Linked
List
10
http://www.simplycs.in http://www.sitcoe.org.in
Basic Linked List Operations
We can treat linked list as an abstract data type and perform following basic
operations.
1. Creating Linked List
2. Traversing Linked List
3. Printing Linked List
4. Counting Number of Nodes in Linked List
5. Searching Element in Linked List
6. Concatenating two Linked List
7. Inserting element into Linked List (Start, end and Specific Position)
8. Deleting elements from Linked List (Start, End and Specific Position)
9. And Many more operations.
11
http://www.simplycs.in http://www.sitcoe.org.in
1. Creating Linked List
12
 Linked List is Created using Dynamic Memory Allocation
 In Following Create Function is Used to Create the Linked List. It return address
of Memory block reserved with size node to main function.
 Variable HEAD, head, p are having storage class as node *. It can store address
of node that has been created dynamically.
 sizeof(node) indicates storage requirement to store a node.
 malloc(sizeof(node)) returns the address of allocated memory block and it is
assigned to variable head;
 If head==NULL, it means memory block not reserved hence linked list empty.
 Type casting operator (node *) used before malloc tells memory block of size
node.
 Write a c program to create Linked list with user defined no of nodes.
http://www.simplycs.in http://www.sitcoe.org.in
typedef struct node // Create Node using structure
{
int data;
struct node *next;
}node;
node *create (int n);
void main() // Main Function
{
int n, i;
node *HEAD;
clrscr();
HEAD->next=NULL; // Linked List Empty
printf(“nt No. of Items:”);
scanf(“%d”,&n);
HEAD=create(n);
printf(“nt LL Created from Address : %u”, HEAD);
getch();
}
13
node *create(int n)
{
node *p, *head;
int i;
head=(node *)malloc(sizeof(node)); // 1st node
head->next=NULL;
printf(“nt Enter Data1:”);
scanf(“%d”,&(head->data));
p=head;
// For Remaining Nodes
for(i=1;i<n;i++)
{
p->next=(node *)malloc(sizeof(node));
p=p->next;
printf(“nt Enter Data%d:”,i+1);
scanf(“%d”,&(p->data));
p->next=NULL;
}
return head;
}
2. Traversing Linked List
14
 Traversal of Linked list always starts with First Node.
 Initially pointer type variable is assigned to First Node(HEAD).
p= HEAD;
 In order to travel linked list in the forward direction, pointer is traversed
through all the nodes.
 Stop at node where address for next gets as NULL.
p=HEAD;
while(p!=NULL)
p=p->next;
40 2000 50 3000 60 NULL
0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD=
http://www.simplycs.in http://www.sitcoe.org.in
3. Counting Number of Nodes in Linked List
15
 Take 1 variable, initialize to 0 (ex. count=0)
 Traverse the linked list from start node to last node and for each node do
count++.
int count (node *p)
{
int count=0;
while(p!=NULL)
{
count=count+1;
p=p->next;
}
return(count);
}
40 2000 50 3000 60 NULL
0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD=
http://www.simplycs.in http://www.sitcoe.org.in
4. Print all the Nodes from List
16
 Traverse the linked list from start node to last node and print each node.
 Below function traverse entire linked list and while traversing it prints integer
data stored in the node.
void print(node *p)
{
while(p!=NULL)
{
printf(“<- %d ->”,p->data);
p=p->next;
}
}
40 2000 50 3000 60 NULL
0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD=
http://www.simplycs.in http://www.sitcoe.org.in
5. Search Node in Linked List
17
 In order to search an element in linked list, we start traversing the from first node.
 Traversal ends with success if element found(1), if not it ends with failure (0).
 Below function search the entire linked list for specific element, if it is found it returns
1 else 0.
int search(node *p, int x)
{
while(p!=NULL)
{
if(p->data==x)
return(1);
p=p->next;
}
return(0);
}
40 2000 50 3000 60 NULL
0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD=
http://www.simplycs.in http://www.sitcoe.org.in
6. Concatenating two Linked Lists.
18
 Lets Assume 2 linked list with 2 different heads- HEAD1 and HEAD2
 If First Linked List is Empty, return HEAD2
 If Second Linked List is Empty, return HEAD1
 Store the address of HEAD1 in Pointer variable, say p.
 Start Traversing first linked list and go to last node whose address field is NULL and Replace that
NULL as HEAD2.
 Return HEAD1
40 2000 50 3000 60 NULL
3500 2500 1500
HEAD2
Linked List 2
40 2000 50 3000 60 3500
1000 2000 3000
HEAD
Concatenated Linked List
40 2000 50 3000 60 NULL
3500 2500 1500
40 2000 50 3000 60 NULL
1000 2000 3000
HEAD1
Linked List1
http://www.simplycs.in http://www.sitcoe.org.in
19
node *concatenate(node *head1, node * head2)
{
node *p;
if(HEAD1==NULL)
return HEAD2;
if(HEAD2==NULL)
return HEAD1;
p=HEAD1;
40 2000 50 3000 60 NULL
3500 2500 1500
HEAD2
Linked List 2
40 2000 50 3000 60 NULL
1000 2000 3000
HEAD1
Linked List1
while(p!=NULL)
p=p->next;
p->next=HEAD2;
return HEAD1;
}
http://www.simplycs.in http://www.sitcoe.org.in
7. Insertion into Linked List
20
Insertion of new item, say x into Linked List has following 3 situations:
1. Insertion at the front of Linked List (Before First Node)
2. Insertion at the end of Linked List (After Last Node)
3. Insertion at Specific Position (Middle) of Linked List
40 2000 50 3000 60 NULL
2000 3000HEAD=1000
1. Algorithm for Placing new item at the front (Beginning) of Linked List
1. Obtain a space for New Node
2. Assign data to data field of new node
3. Set the next field of new node to HEAD / Beginning of linked list.
4. set New HEAD as address of new node
21
40 2000 50 3000 60 NULL
2000 3000HEAD=0500
1. Algorithm for Placing new item at the front (Beginning) of Linked List
X 1000
10000500
node *insert_beg(node *head, int x)
{
node *p;
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=head;
head=p;
return head;
}
http://www.simplycs.in http://www.sitcoe.org.in
22
2. Algorithm for Placing new item at the end of Linked List
node *insert_end(node *head, int x)
{
node *p, *q;
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=NULL;
if(head==NULL);
return p;
1. Obtain a space for New Node. Take node *p, *q; p= (node *)malloc(sizeof(node));
2. Assign data to data field of new node p->data=x;
3. Set the next field to NULL. p->next=NULL;
4. If head==NULL, return p.
5. Else do q=head and Traverse the list to last node copy q=p; and return head;
q=head;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
return head;
}
http://www.simplycs.in http://www.sitcoe.org.in
23
3. Algorithm for Placing new item at given specific location of Linked List
node *insert_loc(node *head, int x, int loc)
{ node *p, *q;
int i;
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=NULL;
q=head;
1. Obtain a space for New Node. Take node *p, *q; p= (node *)malloc(sizeof(node));
2. Assign data to data field of new node p->data=x;
3. Set the next field to NULL. P->next=NULL;
4. Set q= head and go to Position a pointer to loc-1 node using q pointer.
5. Set p->next= q->next
6. Set q->next=p;
7. Stop
for(i=1;i<(loc-1);i++)
{
if(q!=NULL)
q=q->next;
}
p->next=q->next; q->next=p; return head;
}
8. Deletion of item from Linked List
24
deletion of item is even easier than insertion, as only one pointer needs to change. It
has following 3 situations:
1. Deletion the first item
2. Deleting the Last Item
3. Deleting from the Middle of List
40 2000 50 3000 60 NULL
2000 3000HEAD=1000
1. Algorithm for Deleting First Item from Linked List
1. Store the address of First Node(HEAD) into Pointer variable, say p
2. Move HEAD to the Next Node
3. Free the node whose address is stored in pointer p.
4. set New HEAD as address of new node
25
40 2000 50 3000 60 NULL
2000 3000HEAD=0500
1. Algorithm for Deleting First Item from Linked List
X 1000
10000500
node *delete_beg(node *head, int x) // x item to be deleted
{
node *p;
if(x==head->data) {
p=head;
head=head->next;
free(p);
}
return head;
}
http://www.simplycs.in http://www.sitcoe.org.in
26
40 2000 50 3000 60 NULL
2000 3000HEAD=0500
2. Algorithm for Deleting Middle Node from Linked List
X 1000
10000500
1. Store the address of preceding node into Pointer variable, say p. Node to be
deleted is marked as key node, say q.
2. Store the Address of Key node in pointer variable, say q so that it can be
freed later on.
3. Mark the Successor of Key node as a successor of the node pointed by p.
4. Free q.
http://www.simplycs.in http://www.sitcoe.org.in
27
40 2000 50 3000 60 NULL
2000 3000HEAD=0500
3. Algorithm for Last Node from Linked List
X 1000
10000500
1. If the First node itself is last node then
make the linked list empty.
If(head->next==NULL)
{ free(head);
HEAD=NULL; goto step 4;
}
2. Otherwise, position pointer q on second
last node.
q=head;
while(q->next->next!=NULL)
{
http://www.simplycs.in http://www.sitcoe.org.in
q=q->next;
}
3. Delete the last node.
p=q->next;
free(p);
q->next=NULL;
4. Stop
Circular Linked List
 Circular Linked List is a variation of Linked list, in which last node is connected back to first
node.
 Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
 Queue Data Structure can be implemented using Circular Linked lIst.
Singly Linked List as Circular
 In singly linked list, the next pointer of the last node points to the first node.
28
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List as Circular
 In doubly linked list, the next pointer of the last node points to the first node and the
previous pointer of the first node points to the last node making the circular in both
directions.
As per the above illustration, following are the important points to be considered.
 The last node's next field points to the first node of the list in both cases of singly as
well as doubly linked list.
 The first node's previous points to the last node of the list in case of doubly linked list.
29
http://www.simplycs.in http://www.sitcoe.org.in
Basic Operations on Circular Linked List
Following are the important operations supported by a
circular list.
 insert − Inserts an element at the start of the list.
 delete − Deletes an element from the start of the list.
 display − Displays the list.
30
http://www.simplycs.in http://www.sitcoe.org.in
#include<stdio.h>
#include<conio.h>
typedef struct cnode
{
int data;
struct cnode *next;
}cnode;
cnode *insert_cll_end(cnode *h);
cnode *create_cll(int n);
void display_cll(cnode *h);
void main()
{
cnode *HEAD;
int n,i; 31
http://www.simplycs.in http://www.sitcoe.org.in
Create Circular Linked List
clrscr();
printf("nt Enter Number of Nodes:");
scanf("%d",&n);
HEAD=create_cll(n);
printf("ntCircular linked list is created
with start= %u",HEAD);
getch();
display_cll(HEAD);
getch();
HEAD=insert_cll_end(HEAD);
getch();
display_cll(HEAD);
getch();
}
cnode *create_cll(int n)
{
int i;
cnode *h,*p; // creating 1st node
h=(cnode *)malloc(sizeof(cnode));
printf("nt Enter Data1:");
scanf("%d",&(h->data));
h->next=h;
p=h;
for(i=1;i<n;i++) // For reminaing Nodes;
{
p->next=(cnode
*)malloc(sizeof(cnode));
p=p->next;
printf("nt Enter Data%d:",i+1);
scanf("%d",&(p->data));
32
http://www.simplycs.in http://www.sitcoe.org.in
p->next=h;
}
return h;
}
void display_cll(cnode *h)
{
cnode*p;
p=h;
printf("n");
while(p->next!=h)
{
printf("t%d(%u):%u",p->data,p,p->next);
p=p->next;
}
printf("t%d(%u):%u",p->data,p,p->next);
}
cnode *insert_cll_end(cnode *h)
{
cnode *p;
p=h;
while(p->next!=h)
{
p=p->next;
}
p->next=(cnode *)malloc(sizeof(cnode));
p=p->next;
printf("nt Enter Data to insert at end:");
scanf("%d",&(p->data));
p->next=h;
return h;
}
33
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
 In Singly Linked list, we can easily move in the direction of link.
 Finding a node, preceding any node is time consuming process. The only way to find preceding
node is by starting at beginning of the list.
 Solution is Doubly Linked List.
 Each node has two address fields, one to point address of next element and one to point
address of previous element.
 Node is Doubly Linked list has 3 fields
data, prev and next
34
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
 Advantages of DLL over SLL
1) A DLL can be traversed in both forward and backward direction.
2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given.
In DLL, to delete a node, pointer to the previous node is needed. To get this previous node,
sometimes the list is traversed. In DLL, we can get the previous node using previous pointer.
 Disadvantages of DLL over SLL
1) Every node of DLL Require extra space for an previous pointer.
2) All operations require an extra pointer previous to be maintained. For example, in insertion,
we need to modify previous pointers together with next pointers.
35
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
36
☀ In double linked list, the first node must be always pointed by head.
☀ Always the previous field of the first node must be NULL.
☀ Always the next field of the last node must be NULL.
Node Representation –
typedef struct dnode
{
int data;
struct node *prev;
struct node *next;
}dnode;
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Operations
In a double linked list, we perform the following operations...
 Insertion
 Deletion
 Display
Insertion
In a double linked list, the insertion operation can be performed in three ways as
follows...
 Inserting At Beginning of the list
 Inserting At End of the list
 Inserting At Specific location in the list
37
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the
double linked list...
 Step 1: Create a newNode with given value and newNode → previous
as NULL.
 Step 2: Check whether list is Empty (head == NULL)
 Step 3: If it is Empty then, assign NULL to newNode → next and
newNode to head.
 Step 4: If it is not Empty then, assign head to newNode → next and
newNode to head.
38
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Inserting At End of the list
We can use the following steps to insert a new node at end of the double linked
list...
 Step 1: Create a newNode with given value and newNode → next as NULL.
 Step 2: Check whether list is Empty (head == NULL)
 Step 3: If it is Empty, then assign NULL to newNode → previous and
newNode to head.
 Step 4: If it is not Empty, then, define a node pointer temp and initialize
with head.
 Step 5: Keep moving the temp to its next node until it reaches to the last
node in the list (until temp → next is equal to NULL).
 Step 6: Assign newNode to temp → next and temp to newNode → previous.
39
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the double linked list...
 Step 1: Create a newNode with given value.
 Step 2: Check whether list is Empty (head == NULL)
 Step 3: If it is Empty then, assign NULL to newNode → previous & newNode → next and
newNode to head.
 Step 4: If it is not Empty then, define two node pointers temp1 & temp2 and initialize
temp1 with head.
 Step 5: Keep moving the temp1 to its next node until it reaches to the node after which
we want to insert the newNode (until temp1 → data is equal to location, here location is
the node value after which we want to insert the newNode).
 Step 6: Every time check whether temp1 is reached to the last node. If it is reached to
the last node then display 'Given node is not found in the list!!! Insertion not
possible!!!' and terminate the function. Otherwise move the temp1 to next node.
 Step 7: Assign temp1 → next to temp2, newNode to temp1 → next, temp1 to newNode
→ previous, temp2 to newNode → next and newNode to temp2 → previous.
40
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Deletion
In a double linked list, the deletion operation can be performed in three ways as follows...
 Deleting from Beginning of the list
 Deleting from End of the list
 Deleting a Specific Node
Deleting from Beginning of the list
 We can use the following steps to delete a node from beginning of the double linked list...
 Step 1: Check whether list is Empty (head == NULL)
 Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
 Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with head.
 Step 4: Check whether list is having only one node (temp → previous is equal to temp →
next)
 Step 5: If it is TRUE, then set head to NULL and delete temp (Setting Empty list
conditions)
 Step 6: If it is FALSE, then assign temp → next to head, NULL to head → previous and
delete temp. 41
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Deleting from End of the list
We can use the following steps to delete a node from end of the double linked list...
 Step 1: Check whether list is Empty (head == NULL)
 Step 2: If it is Empty, then display 'List is Empty!!! Deletion is not possible' and
terminate the function.
 Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with
head.
 Step 4: Check whether list has only one Node (temp → previous and temp →
next both are NULL)
 Step 5: If it is TRUE, then assign NULL to head and delete temp. And terminate
from the function. (Setting Empty list condition)
 Step 6: If it is FALSE, then keep moving temp until it reaches to the last node in
the list. (until temp → next is equal to NULL)
 Step 7: Assign NULL to temp → previous → next and delete temp.42
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the double
linked list...
 Step 1: Check whether list is Empty (head == NULL)
 Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
 Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize
with head.
 Step 4: Keep moving the temp until it reaches to the exact node to be
deleted or to the last node.
 Step 5: If it is reached to the last node, then display 'Given node not
found in the list! Deletion not possible!!!' and terminate the fuction.
 Step 6: If it is reached to the exact node which we want to delete, then
check whether list is having only one node or not
43
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Step 7: If list has only one node and that is the node which is to be deleted then set head to
NULL and delete temp (free(temp)).
Step 8: If list contains multiple nodes, then check whether temp is the first node in the list
(temp == head).
Step 9: If temp is the first node, then move the head to the next node (head = head → next),
set head of previous to NULL (head → previous = NULL) and delete temp.
Step 10: If temp is not the first node, then check whether it is the last node in the list (temp
→ next == NULL).
Step 11: If temp is the last node then set temp of previous of next to NULL (temp → previous
→ next = NULL) and delete temp (free(temp)).
Step 12: If temp is not the first node and not the last node, then set temp of previous of next
to temp of next (temp → previous → next = temp → next), temp of next of previous to temp
of previous (temp → next → previous = temp → previous) and delete temp (free(temp)).
44
http://www.simplycs.in http://www.sitcoe.org.in
Doubly Linked List
Displaying a Double Linked List
We can use the following steps to display the elements of a double linked list...
 Step 1: Check whether list is Empty (head == NULL)
 Step 2: If it is Empty, then display 'List is Empty!!!' and terminate the function.
 Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize with head.
 Step 4: Display 'NULL <--- '.
 Step 5: Keep displaying temp → data with an arrow (<===>) until temp reaches to the
last node
 Step 6: Finally, display temp → data with arrow pointing to NULL (temp → data --->
NULL).
45
http://www.simplycs.in http://www.sitcoe.org.in
Applications of Linked List
 Linked list are frequently used to implement other data structures like tree, graphs and
heaps.
 Linked can be used to create dynamic stack and queue which can grow and shrink at run
time.
 Linked list can used to store and process the polynomials.
 Coefficient and power stored as data and link pointer points to next term in the polynomial.
 Linked list are normally implemented using pointers. Some Languages does not support
pointer like Visual Basic, Fortran etc. In these Array is used to implement LL.46
http://www.simplycs.in http://www.sitcoe.org.in
Applications of Linked List
47
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
 The major problem with the stack implemented using array is, it works only for fixed
number of data values.
 That means the amount of data must be specified at the beginning of the implementation
itself.
 Stack implemented using array is not suitable, when we don't know the size of data which
we are going to use.
 A stack data structure can be implemented by using linked list data structure. The stack
implemented using linked list can work for unlimited number of values.
 That means, stack implemented using linked list works for variable size of data. So, there
is no need to fix the size at the beginning of the implementation.
 The Stack implemented using linked list can organize as many data values as we want.
48
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
 In linked list implementation of a stack, every new element is inserted as
'top' element. That means every newly inserted element is pointed by
'top'.
 Whenever we want to remove an element from the stack, simply remove
the node which is pointed by 'top' by moving 'top' to its next node in the
list.
 The next field of the first element must be always NULL.
 In above example, the last inserted node is 99 and
the first inserted node is 25.
The order of elements inserted is 25, 32,50 and 99.
49
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
Operations
To implement stack using linked list, we need to set the following things
before implementing actual operations.
 Step 1: Include all the header files which are used in the program. And
declare all the user defined functions.
 Step 2: Define a 'Node' structure with two members data and next.
 Step 3: Define a Node pointer 'top' and set it to NULL.
 Step 4: Implement the main method by displaying Menu with list of
operations and make suitable function calls in the main method.
50
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
push(value) - Inserting an element into the Stack
We can use the following steps to insert a new node into the stack...
 Step 1: Create a newNode with given value.
 Step 2: Check whether stack is Empty (top == NULL)
 Step 3: If it is Empty, then set newNode → next = NULL.
 Step 4: If it is Not Empty, then set newNode → next = top.
 Step 5: Finally, set top = newNode.
pop() - Deleting an Element from a Stack
We can use the following steps to delete a node from the stack...
 Step 1: Check whether stack is Empty (top == NULL).
 Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!"
and terminate the function
 Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
 Step 4: Then set 'top = top → next'.
 Step 7: Finally, delete 'temp' (free(temp)). 51
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
display() - Displaying stack of elements
We can use the following steps to display the elements (nodes) of a stack...
 Step 1: Check whether stack is Empty (top == NULL).
 Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the
function.
 Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize
with top.
 Step 4: Display 'temp → data --->' and move it to the next node. Repeat
the same until temp reaches to the first node in the stack (temp → next
!= NULL).
 Step 4: Finally! Display 'temp → data ---> NULL'.
52
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Stack using Linked List
53
http://www.simplycs.in http://www.sitcoe.org.in
#include<conio.h>
#include<stdio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
clrscr();
printf("n:: Stack using Linked List
::n");
while(1){
printf("n****** MENU ******n");
printf("1. Pushn2. Popn3. Displayn4. Exitn");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be
insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("nWrong selection!!!
Please try again!!!n");
}
}
}
How to Implement Stack using Linked List
54
http://www.simplycs.in http://www.sitcoe.org.in
void push(int value)
{
struct Node *p;
p = (struct Node*)malloc(sizeof(struct
Node));
p->data = value;
if(top == NULL)
p->next = NULL;
else
p->next = top;
top = p;
printf("nInsertion is Success!!!n");
}
void pop()
{
if(top == NULL)
{
printf("nStack is Empty!!!n");
}
else
{
struct Node *temp = top;
printf("nDeleted element: %d",
temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("nStack is Empty!!!n");
else{
struct Node *p = top;
while(p->next != NULL){
printf("%d--->",p->data);
p = p-> next;
}
printf("%d--->NULL",p->data);
}
55
How to Implement Queue using Linked List
 The major problem with the queue implemented using array is, It will work for only fixed
number of data.
 That means, the amount of data must be specified in the beginning itself.
 Queue using array is not suitable when we don't know the size of data which we are going to
use. A queue data structure can be implemented using linked list data structure.
 The queue which is implemented using linked list can work for unlimited number of
values. That means, queue using linked list can work for variable size of data (No need to
fix the size at beginning of the implementation).
 The Queue implemented using linked list can organize as many data values as we want.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear'
and the first node is always pointed by 'front'.
 In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted
node is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50.
56
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Queue using Linked List
Operations
To implement queue using linked list, we need to set the following things before
implementing actual operations.
 Step 1: Include all the header files which are used in the program. And declare all the
user defined functions.
 Step 2: Define a 'Node' structure with two members data and next.
 Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
 Step 4: Implement the main method by displaying Menu of list of operations and make
suitable function calls in the main method to perform user selected operation.
enQueue(value) - Inserting an element into the Queue
 We can use the following steps to insert a new node into the queue...
 Step 1: Create a newNode with given value and set 'newNode → next' to NULL.
 Step 2: Check whether queue is Empty (rear == NULL)
 Step 3: If it is Empty then, set front = newNode and rear = newNode.
 Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.
57
http://www.simplycs.in http://www.sitcoe.org.in
How to Implement Queue using Linked List
deQueue() - Deleting an Element from Queue
We can use the following steps to delete a node from the queue...
 Step 1: Check whether queue is Empty (front == NULL).
 Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function
 Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
 Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).
display() - Displaying the elements of Queue
We can use the following steps to display the elements (nodes) of a queue...
 Step 1: Check whether queue is Empty (front == NULL).
 Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
 Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
 Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
 Step 4: Finally! Display 'temp → data ---> NULL'. Do Program58
http://www.simplycs.in http://www.sitcoe.org.in

More Related Content

What's hot

Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....Shail Nakum
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy TutorialAfzal Badshah
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First SearchKevin Jadiya
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - GraphMadhu Bala
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Presentation on Data Structure
Presentation on Data StructurePresentation on Data Structure
Presentation on Data StructureA. N. M. Jubaer
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 
Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked ListSayantan Sur
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arorakulachihansraj
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 

What's hot (20)

Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
stack & queue
stack & queuestack & queue
stack & queue
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
single linked list
single linked listsingle linked list
single linked list
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Linked lists
Linked listsLinked lists
Linked lists
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Presentation on Data Structure
Presentation on Data StructurePresentation on Data Structure
Presentation on Data Structure
 
Stack
StackStack
Stack
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 
Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked List
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 

Viewers also liked

Trees data structure
Trees data structureTrees data structure
Trees data structureSumit Gupta
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked listFahd Allebdi
 
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)John C. Havens
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
6. Linked list - Data Structures using C++ by Varsha Patil
6. Linked list - Data Structures using C++ by Varsha Patil6. Linked list - Data Structures using C++ by Varsha Patil
6. Linked list - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8sumitbardhan
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureBalwant Gorad
 
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)Lovelyn Rose
 
Double linked list
Double linked listDouble linked list
Double linked listraviahuja11
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAbhishek L.R
 
Open Legal Data Workshop at Stanford
Open Legal Data Workshop at StanfordOpen Legal Data Workshop at Stanford
Open Legal Data Workshop at StanfordHarry Surden
 
Harry Surden - Artificial Intelligence and Law Overview
Harry Surden - Artificial Intelligence and Law OverviewHarry Surden - Artificial Intelligence and Law Overview
Harry Surden - Artificial Intelligence and Law OverviewHarry Surden
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017Carol Smith
 

Viewers also liked (16)

Trees data structure
Trees data structureTrees data structure
Trees data structure
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked list
 
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)
Individual-In-The-Loop (for Ethically Aligned Artificial Intelligence)
 
linked list
linked list linked list
linked list
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
6. Linked list - Data Structures using C++ by Varsha Patil
6. Linked list - Data Structures using C++ by Varsha Patil6. Linked list - Data Structures using C++ by Varsha Patil
6. Linked list - Data Structures using C++ by Varsha Patil
 
7 Myths of AI
7 Myths of AI7 Myths of AI
7 Myths of AI
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
 
Cyber Crime
Cyber CrimeCyber Crime
Cyber Crime
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)
Insertion and Deletion in Binary Search Trees (using Arrays and Linked Lists)
 
Double linked list
Double linked listDouble linked list
Double linked list
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Open Legal Data Workshop at Stanford
Open Legal Data Workshop at StanfordOpen Legal Data Workshop at Stanford
Open Legal Data Workshop at Stanford
 
Harry Surden - Artificial Intelligence and Law Overview
Harry Surden - Artificial Intelligence and Law OverviewHarry Surden - Artificial Intelligence and Law Overview
Harry Surden - Artificial Intelligence and Law Overview
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
 

Similar to Linked List, Types of Linked LIst, Various Operations, Applications of Linked List

Similar to Linked List, Types of Linked LIst, Various Operations, Applications of Linked List (20)

Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
DS Unit 2.ppt
DS Unit 2.pptDS Unit 2.ppt
DS Unit 2.ppt
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
Linked List
Linked ListLinked List
Linked List
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
Linked list
Linked listLinked list
Linked list
 
Linked list (introduction) 1
Linked list (introduction) 1Linked list (introduction) 1
Linked list (introduction) 1
 
Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
Data structure
Data structureData structure
Data structure
 
Linked list.docx
Linked list.docxLinked list.docx
Linked list.docx
 
Data structure
 Data structure Data structure
Data structure
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
 
1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
 
Linked list
Linked list Linked list
Linked list
 

Recently uploaded

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 

Recently uploaded (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 

Linked List, Types of Linked LIst, Various Operations, Applications of Linked List

  • 1. Linked List in Data Structure By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra http://www.simplycs.in http://www.sitcoe.org.in
  • 2. Linked List  Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers.  Why Linked List? Arrays can be used to store linear data of similar types, but arrays have following limitations. 1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage. 2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted. 2 http://www.simplycs.in http://www.sitcoe.org.in
  • 3.  For example, in a system if we maintain a sorted list of IDs in an array id[].  id[] = [1000, 1010, 1050, 2000, 2040].  And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). Deletion is also expensive with arrays until unless some special techniques are used.  For example, to delete 1010 in id[], everything after 1010 has to be moved. 3 http://www.simplycs.in http://www.sitcoe.org.in
  • 4.  Advantages Linked List over arrays 1) Dynamic size 2) Ease of insertion/deletion  Drawbacks of Linked List: 1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists. 2) Extra memory space for a pointer is required with each element of the list. 4 http://www.simplycs.in http://www.sitcoe.org.in
  • 5. Representation of Linked List in C:  A linked list is represented by a pointer to the first node of the linked list.  The first node is called head. If the linked list is empty, then value of head is NULL.  Each node in a list consists of at least two parts: 1) data 2) pointer to the next node  In C, we can represent a node using structures. Below is an example of a linked list node with an integer data.  In C#/Java, LinkedList can be represented as a class and a Node as a separate class. The LinkedList class contains a reference of Node class type.  Write C Program to Create Linked List. Data Address of Next Node Data Data DataAddress of Next Node Address of Next Node Address of Next Node 40 2000 50 3000 60 NULL 0x1000 0x2000 0x3000 Address of Last Node is NULLAddress of Head Node 5
  • 6. Implementation of Linked List –  Structure is used to define a node.  Node is Collection of Data and Address to Next Node.  Address of Next Node can be Stored in pointer type variable.  Ex. typedef struct node { int data; struct node *next; }node;  It is Self Referential Structure in C.  It is Assumed that, type of data stored in each node is of integer type.  In C Programming, Memory can be acquired through use of standard library functions malloc() and calloc() from stdlib.h header file.  To Free Memory aquired, free(address) function is used. Memory Allocation for node using malloc() Function- node *p; p=(node *)malloc(sizeof(node)); p->data=40; p->next=NULL; 40 NULL p data Next address 6 http://www.simplycs.in http://www.sitcoe.org.in
  • 7. #include<stdio.h> #include<stdlib.h> //calloc/malloc/free struct Node { int data; struct Node *next; }; // Program to create a simple linked // list with 3 nodes int main() { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; // allocate 3 nodes in the heap head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; //assign data in first node head->next = second; // Link first node with the second node /* data has been assigned to data part of first block (block pointed by head). And next pointer of first block points to second. So they both are linked. head second third | | | | | | +---+---+ +----+----+ +-----+----+ | 1 | o----->| # | # | | # | # | +---+---+ +----+----+ +-----+----+ */ second->data = 2; //assign data to second node second->next = third; // Link second node with the third node third->data = 3; //assign data to third node third->next = NULL; return 0; } // A simple C program to introduce a linked list 7 http://www.simplycs.in http://www.sitcoe.org.in
  • 8. Types of Linked List There are three common types of Linked List.  Singly Linked List  Doubly Linked List  Circular Linked List Singly Linked List  It is the most common. Each node has data and a pointer to the next node. typedef struct node { int data; struct node *next; }node; Node Representation in singly Linked List 8 http://www.simplycs.in http://www.sitcoe.org.in
  • 9. Doubly Linked List  We add a pointer to the previous node in a doubly linked list. Thus, we can go in either direction: forward or backward. typedef struct node { int data; struct node *next; struct node *prev; }node; Node Representation in doubly Linked List 9 http://www.simplycs.in http://www.sitcoe.org.in
  • 10. Circular Linked List  A circular linked list is a variation of linked list in which the last element is linked to the first element. This forms a circular loop. A circular linked list can be either singly linked or doubly linked.  for Circular singly linked list, next pointer of last item points to the first item  In Circular doubly linked list, prev pointer of first item points to last item as well. typedef struct node { int data; struct node *next; }node; Node Representation in Circular Linked List 10 http://www.simplycs.in http://www.sitcoe.org.in
  • 11. Basic Linked List Operations We can treat linked list as an abstract data type and perform following basic operations. 1. Creating Linked List 2. Traversing Linked List 3. Printing Linked List 4. Counting Number of Nodes in Linked List 5. Searching Element in Linked List 6. Concatenating two Linked List 7. Inserting element into Linked List (Start, end and Specific Position) 8. Deleting elements from Linked List (Start, End and Specific Position) 9. And Many more operations. 11 http://www.simplycs.in http://www.sitcoe.org.in
  • 12. 1. Creating Linked List 12  Linked List is Created using Dynamic Memory Allocation  In Following Create Function is Used to Create the Linked List. It return address of Memory block reserved with size node to main function.  Variable HEAD, head, p are having storage class as node *. It can store address of node that has been created dynamically.  sizeof(node) indicates storage requirement to store a node.  malloc(sizeof(node)) returns the address of allocated memory block and it is assigned to variable head;  If head==NULL, it means memory block not reserved hence linked list empty.  Type casting operator (node *) used before malloc tells memory block of size node.  Write a c program to create Linked list with user defined no of nodes. http://www.simplycs.in http://www.sitcoe.org.in
  • 13. typedef struct node // Create Node using structure { int data; struct node *next; }node; node *create (int n); void main() // Main Function { int n, i; node *HEAD; clrscr(); HEAD->next=NULL; // Linked List Empty printf(“nt No. of Items:”); scanf(“%d”,&n); HEAD=create(n); printf(“nt LL Created from Address : %u”, HEAD); getch(); } 13 node *create(int n) { node *p, *head; int i; head=(node *)malloc(sizeof(node)); // 1st node head->next=NULL; printf(“nt Enter Data1:”); scanf(“%d”,&(head->data)); p=head; // For Remaining Nodes for(i=1;i<n;i++) { p->next=(node *)malloc(sizeof(node)); p=p->next; printf(“nt Enter Data%d:”,i+1); scanf(“%d”,&(p->data)); p->next=NULL; } return head; }
  • 14. 2. Traversing Linked List 14  Traversal of Linked list always starts with First Node.  Initially pointer type variable is assigned to First Node(HEAD). p= HEAD;  In order to travel linked list in the forward direction, pointer is traversed through all the nodes.  Stop at node where address for next gets as NULL. p=HEAD; while(p!=NULL) p=p->next; 40 2000 50 3000 60 NULL 0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD= http://www.simplycs.in http://www.sitcoe.org.in
  • 15. 3. Counting Number of Nodes in Linked List 15  Take 1 variable, initialize to 0 (ex. count=0)  Traverse the linked list from start node to last node and for each node do count++. int count (node *p) { int count=0; while(p!=NULL) { count=count+1; p=p->next; } return(count); } 40 2000 50 3000 60 NULL 0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD= http://www.simplycs.in http://www.sitcoe.org.in
  • 16. 4. Print all the Nodes from List 16  Traverse the linked list from start node to last node and print each node.  Below function traverse entire linked list and while traversing it prints integer data stored in the node. void print(node *p) { while(p!=NULL) { printf(“<- %d ->”,p->data); p=p->next; } } 40 2000 50 3000 60 NULL 0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD= http://www.simplycs.in http://www.sitcoe.org.in
  • 17. 5. Search Node in Linked List 17  In order to search an element in linked list, we start traversing the from first node.  Traversal ends with success if element found(1), if not it ends with failure (0).  Below function search the entire linked list for specific element, if it is found it returns 1 else 0. int search(node *p, int x) { while(p!=NULL) { if(p->data==x) return(1); p=p->next; } return(0); } 40 2000 50 3000 60 NULL 0x1000 0x2000 0x3000 Address of Last Node is NULLHEAD= http://www.simplycs.in http://www.sitcoe.org.in
  • 18. 6. Concatenating two Linked Lists. 18  Lets Assume 2 linked list with 2 different heads- HEAD1 and HEAD2  If First Linked List is Empty, return HEAD2  If Second Linked List is Empty, return HEAD1  Store the address of HEAD1 in Pointer variable, say p.  Start Traversing first linked list and go to last node whose address field is NULL and Replace that NULL as HEAD2.  Return HEAD1 40 2000 50 3000 60 NULL 3500 2500 1500 HEAD2 Linked List 2 40 2000 50 3000 60 3500 1000 2000 3000 HEAD Concatenated Linked List 40 2000 50 3000 60 NULL 3500 2500 1500 40 2000 50 3000 60 NULL 1000 2000 3000 HEAD1 Linked List1 http://www.simplycs.in http://www.sitcoe.org.in
  • 19. 19 node *concatenate(node *head1, node * head2) { node *p; if(HEAD1==NULL) return HEAD2; if(HEAD2==NULL) return HEAD1; p=HEAD1; 40 2000 50 3000 60 NULL 3500 2500 1500 HEAD2 Linked List 2 40 2000 50 3000 60 NULL 1000 2000 3000 HEAD1 Linked List1 while(p!=NULL) p=p->next; p->next=HEAD2; return HEAD1; } http://www.simplycs.in http://www.sitcoe.org.in
  • 20. 7. Insertion into Linked List 20 Insertion of new item, say x into Linked List has following 3 situations: 1. Insertion at the front of Linked List (Before First Node) 2. Insertion at the end of Linked List (After Last Node) 3. Insertion at Specific Position (Middle) of Linked List 40 2000 50 3000 60 NULL 2000 3000HEAD=1000 1. Algorithm for Placing new item at the front (Beginning) of Linked List 1. Obtain a space for New Node 2. Assign data to data field of new node 3. Set the next field of new node to HEAD / Beginning of linked list. 4. set New HEAD as address of new node
  • 21. 21 40 2000 50 3000 60 NULL 2000 3000HEAD=0500 1. Algorithm for Placing new item at the front (Beginning) of Linked List X 1000 10000500 node *insert_beg(node *head, int x) { node *p; p=(node *)malloc(sizeof(node)); p->data=x; p->next=head; head=p; return head; } http://www.simplycs.in http://www.sitcoe.org.in
  • 22. 22 2. Algorithm for Placing new item at the end of Linked List node *insert_end(node *head, int x) { node *p, *q; p=(node *)malloc(sizeof(node)); p->data=x; p->next=NULL; if(head==NULL); return p; 1. Obtain a space for New Node. Take node *p, *q; p= (node *)malloc(sizeof(node)); 2. Assign data to data field of new node p->data=x; 3. Set the next field to NULL. p->next=NULL; 4. If head==NULL, return p. 5. Else do q=head and Traverse the list to last node copy q=p; and return head; q=head; while(q->next!=NULL) { q=q->next; } q->next=p; return head; } http://www.simplycs.in http://www.sitcoe.org.in
  • 23. 23 3. Algorithm for Placing new item at given specific location of Linked List node *insert_loc(node *head, int x, int loc) { node *p, *q; int i; p=(node *)malloc(sizeof(node)); p->data=x; p->next=NULL; q=head; 1. Obtain a space for New Node. Take node *p, *q; p= (node *)malloc(sizeof(node)); 2. Assign data to data field of new node p->data=x; 3. Set the next field to NULL. P->next=NULL; 4. Set q= head and go to Position a pointer to loc-1 node using q pointer. 5. Set p->next= q->next 6. Set q->next=p; 7. Stop for(i=1;i<(loc-1);i++) { if(q!=NULL) q=q->next; } p->next=q->next; q->next=p; return head; }
  • 24. 8. Deletion of item from Linked List 24 deletion of item is even easier than insertion, as only one pointer needs to change. It has following 3 situations: 1. Deletion the first item 2. Deleting the Last Item 3. Deleting from the Middle of List 40 2000 50 3000 60 NULL 2000 3000HEAD=1000 1. Algorithm for Deleting First Item from Linked List 1. Store the address of First Node(HEAD) into Pointer variable, say p 2. Move HEAD to the Next Node 3. Free the node whose address is stored in pointer p. 4. set New HEAD as address of new node
  • 25. 25 40 2000 50 3000 60 NULL 2000 3000HEAD=0500 1. Algorithm for Deleting First Item from Linked List X 1000 10000500 node *delete_beg(node *head, int x) // x item to be deleted { node *p; if(x==head->data) { p=head; head=head->next; free(p); } return head; } http://www.simplycs.in http://www.sitcoe.org.in
  • 26. 26 40 2000 50 3000 60 NULL 2000 3000HEAD=0500 2. Algorithm for Deleting Middle Node from Linked List X 1000 10000500 1. Store the address of preceding node into Pointer variable, say p. Node to be deleted is marked as key node, say q. 2. Store the Address of Key node in pointer variable, say q so that it can be freed later on. 3. Mark the Successor of Key node as a successor of the node pointed by p. 4. Free q. http://www.simplycs.in http://www.sitcoe.org.in
  • 27. 27 40 2000 50 3000 60 NULL 2000 3000HEAD=0500 3. Algorithm for Last Node from Linked List X 1000 10000500 1. If the First node itself is last node then make the linked list empty. If(head->next==NULL) { free(head); HEAD=NULL; goto step 4; } 2. Otherwise, position pointer q on second last node. q=head; while(q->next->next!=NULL) { http://www.simplycs.in http://www.sitcoe.org.in q=q->next; } 3. Delete the last node. p=q->next; free(p); q->next=NULL; 4. Stop
  • 28. Circular Linked List  Circular Linked List is a variation of Linked list, in which last node is connected back to first node.  Both Singly Linked List and Doubly Linked List can be made into a circular linked list.  Queue Data Structure can be implemented using Circular Linked lIst. Singly Linked List as Circular  In singly linked list, the next pointer of the last node points to the first node. 28 http://www.simplycs.in http://www.sitcoe.org.in
  • 29. Doubly Linked List as Circular  In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions. As per the above illustration, following are the important points to be considered.  The last node's next field points to the first node of the list in both cases of singly as well as doubly linked list.  The first node's previous points to the last node of the list in case of doubly linked list. 29 http://www.simplycs.in http://www.sitcoe.org.in
  • 30. Basic Operations on Circular Linked List Following are the important operations supported by a circular list.  insert − Inserts an element at the start of the list.  delete − Deletes an element from the start of the list.  display − Displays the list. 30 http://www.simplycs.in http://www.sitcoe.org.in
  • 31. #include<stdio.h> #include<conio.h> typedef struct cnode { int data; struct cnode *next; }cnode; cnode *insert_cll_end(cnode *h); cnode *create_cll(int n); void display_cll(cnode *h); void main() { cnode *HEAD; int n,i; 31 http://www.simplycs.in http://www.sitcoe.org.in Create Circular Linked List clrscr(); printf("nt Enter Number of Nodes:"); scanf("%d",&n); HEAD=create_cll(n); printf("ntCircular linked list is created with start= %u",HEAD); getch(); display_cll(HEAD); getch(); HEAD=insert_cll_end(HEAD); getch(); display_cll(HEAD); getch(); }
  • 32. cnode *create_cll(int n) { int i; cnode *h,*p; // creating 1st node h=(cnode *)malloc(sizeof(cnode)); printf("nt Enter Data1:"); scanf("%d",&(h->data)); h->next=h; p=h; for(i=1;i<n;i++) // For reminaing Nodes; { p->next=(cnode *)malloc(sizeof(cnode)); p=p->next; printf("nt Enter Data%d:",i+1); scanf("%d",&(p->data)); 32 http://www.simplycs.in http://www.sitcoe.org.in p->next=h; } return h; } void display_cll(cnode *h) { cnode*p; p=h; printf("n"); while(p->next!=h) { printf("t%d(%u):%u",p->data,p,p->next); p=p->next; } printf("t%d(%u):%u",p->data,p,p->next); }
  • 33. cnode *insert_cll_end(cnode *h) { cnode *p; p=h; while(p->next!=h) { p=p->next; } p->next=(cnode *)malloc(sizeof(cnode)); p=p->next; printf("nt Enter Data to insert at end:"); scanf("%d",&(p->data)); p->next=h; return h; } 33 http://www.simplycs.in http://www.sitcoe.org.in
  • 34. Doubly Linked List  In Singly Linked list, we can easily move in the direction of link.  Finding a node, preceding any node is time consuming process. The only way to find preceding node is by starting at beginning of the list.  Solution is Doubly Linked List.  Each node has two address fields, one to point address of next element and one to point address of previous element.  Node is Doubly Linked list has 3 fields data, prev and next 34 http://www.simplycs.in http://www.sitcoe.org.in
  • 35. Doubly Linked List  Advantages of DLL over SLL 1) A DLL can be traversed in both forward and backward direction. 2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given. In DLL, to delete a node, pointer to the previous node is needed. To get this previous node, sometimes the list is traversed. In DLL, we can get the previous node using previous pointer.  Disadvantages of DLL over SLL 1) Every node of DLL Require extra space for an previous pointer. 2) All operations require an extra pointer previous to be maintained. For example, in insertion, we need to modify previous pointers together with next pointers. 35 http://www.simplycs.in http://www.sitcoe.org.in
  • 36. Doubly Linked List 36 ☀ In double linked list, the first node must be always pointed by head. ☀ Always the previous field of the first node must be NULL. ☀ Always the next field of the last node must be NULL. Node Representation – typedef struct dnode { int data; struct node *prev; struct node *next; }dnode; http://www.simplycs.in http://www.sitcoe.org.in
  • 37. Doubly Linked List Operations In a double linked list, we perform the following operations...  Insertion  Deletion  Display Insertion In a double linked list, the insertion operation can be performed in three ways as follows...  Inserting At Beginning of the list  Inserting At End of the list  Inserting At Specific location in the list 37 http://www.simplycs.in http://www.sitcoe.org.in
  • 38. Doubly Linked List Inserting At Beginning of the list We can use the following steps to insert a new node at beginning of the double linked list...  Step 1: Create a newNode with given value and newNode → previous as NULL.  Step 2: Check whether list is Empty (head == NULL)  Step 3: If it is Empty then, assign NULL to newNode → next and newNode to head.  Step 4: If it is not Empty then, assign head to newNode → next and newNode to head. 38 http://www.simplycs.in http://www.sitcoe.org.in
  • 39. Doubly Linked List Inserting At End of the list We can use the following steps to insert a new node at end of the double linked list...  Step 1: Create a newNode with given value and newNode → next as NULL.  Step 2: Check whether list is Empty (head == NULL)  Step 3: If it is Empty, then assign NULL to newNode → previous and newNode to head.  Step 4: If it is not Empty, then, define a node pointer temp and initialize with head.  Step 5: Keep moving the temp to its next node until it reaches to the last node in the list (until temp → next is equal to NULL).  Step 6: Assign newNode to temp → next and temp to newNode → previous. 39 http://www.simplycs.in http://www.sitcoe.org.in
  • 40. Doubly Linked List Inserting At Specific location in the list (After a Node) We can use the following steps to insert a new node after a node in the double linked list...  Step 1: Create a newNode with given value.  Step 2: Check whether list is Empty (head == NULL)  Step 3: If it is Empty then, assign NULL to newNode → previous & newNode → next and newNode to head.  Step 4: If it is not Empty then, define two node pointers temp1 & temp2 and initialize temp1 with head.  Step 5: Keep moving the temp1 to its next node until it reaches to the node after which we want to insert the newNode (until temp1 → data is equal to location, here location is the node value after which we want to insert the newNode).  Step 6: Every time check whether temp1 is reached to the last node. If it is reached to the last node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the function. Otherwise move the temp1 to next node.  Step 7: Assign temp1 → next to temp2, newNode to temp1 → next, temp1 to newNode → previous, temp2 to newNode → next and newNode to temp2 → previous. 40 http://www.simplycs.in http://www.sitcoe.org.in
  • 41. Doubly Linked List Deletion In a double linked list, the deletion operation can be performed in three ways as follows...  Deleting from Beginning of the list  Deleting from End of the list  Deleting a Specific Node Deleting from Beginning of the list  We can use the following steps to delete a node from beginning of the double linked list...  Step 1: Check whether list is Empty (head == NULL)  Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.  Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with head.  Step 4: Check whether list is having only one node (temp → previous is equal to temp → next)  Step 5: If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions)  Step 6: If it is FALSE, then assign temp → next to head, NULL to head → previous and delete temp. 41 http://www.simplycs.in http://www.sitcoe.org.in
  • 42. Doubly Linked List Deleting from End of the list We can use the following steps to delete a node from end of the double linked list...  Step 1: Check whether list is Empty (head == NULL)  Step 2: If it is Empty, then display 'List is Empty!!! Deletion is not possible' and terminate the function.  Step 3: If it is not Empty then, define a Node pointer 'temp' and initialize with head.  Step 4: Check whether list has only one Node (temp → previous and temp → next both are NULL)  Step 5: If it is TRUE, then assign NULL to head and delete temp. And terminate from the function. (Setting Empty list condition)  Step 6: If it is FALSE, then keep moving temp until it reaches to the last node in the list. (until temp → next is equal to NULL)  Step 7: Assign NULL to temp → previous → next and delete temp.42 http://www.simplycs.in http://www.sitcoe.org.in
  • 43. Doubly Linked List Deleting a Specific Node from the list We can use the following steps to delete a specific node from the double linked list...  Step 1: Check whether list is Empty (head == NULL)  Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.  Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize with head.  Step 4: Keep moving the temp until it reaches to the exact node to be deleted or to the last node.  Step 5: If it is reached to the last node, then display 'Given node not found in the list! Deletion not possible!!!' and terminate the fuction.  Step 6: If it is reached to the exact node which we want to delete, then check whether list is having only one node or not 43 http://www.simplycs.in http://www.sitcoe.org.in
  • 44. Doubly Linked List Step 7: If list has only one node and that is the node which is to be deleted then set head to NULL and delete temp (free(temp)). Step 8: If list contains multiple nodes, then check whether temp is the first node in the list (temp == head). Step 9: If temp is the first node, then move the head to the next node (head = head → next), set head of previous to NULL (head → previous = NULL) and delete temp. Step 10: If temp is not the first node, then check whether it is the last node in the list (temp → next == NULL). Step 11: If temp is the last node then set temp of previous of next to NULL (temp → previous → next = NULL) and delete temp (free(temp)). Step 12: If temp is not the first node and not the last node, then set temp of previous of next to temp of next (temp → previous → next = temp → next), temp of next of previous to temp of previous (temp → next → previous = temp → previous) and delete temp (free(temp)). 44 http://www.simplycs.in http://www.sitcoe.org.in
  • 45. Doubly Linked List Displaying a Double Linked List We can use the following steps to display the elements of a double linked list...  Step 1: Check whether list is Empty (head == NULL)  Step 2: If it is Empty, then display 'List is Empty!!!' and terminate the function.  Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize with head.  Step 4: Display 'NULL <--- '.  Step 5: Keep displaying temp → data with an arrow (<===>) until temp reaches to the last node  Step 6: Finally, display temp → data with arrow pointing to NULL (temp → data ---> NULL). 45 http://www.simplycs.in http://www.sitcoe.org.in
  • 46. Applications of Linked List  Linked list are frequently used to implement other data structures like tree, graphs and heaps.  Linked can be used to create dynamic stack and queue which can grow and shrink at run time.  Linked list can used to store and process the polynomials.  Coefficient and power stored as data and link pointer points to next term in the polynomial.  Linked list are normally implemented using pointers. Some Languages does not support pointer like Visual Basic, Fortran etc. In these Array is used to implement LL.46 http://www.simplycs.in http://www.sitcoe.org.in
  • 47. Applications of Linked List 47 http://www.simplycs.in http://www.sitcoe.org.in
  • 48. How to Implement Stack using Linked List  The major problem with the stack implemented using array is, it works only for fixed number of data values.  That means the amount of data must be specified at the beginning of the implementation itself.  Stack implemented using array is not suitable, when we don't know the size of data which we are going to use.  A stack data structure can be implemented by using linked list data structure. The stack implemented using linked list can work for unlimited number of values.  That means, stack implemented using linked list works for variable size of data. So, there is no need to fix the size at the beginning of the implementation.  The Stack implemented using linked list can organize as many data values as we want. 48 http://www.simplycs.in http://www.sitcoe.org.in
  • 49. How to Implement Stack using Linked List  In linked list implementation of a stack, every new element is inserted as 'top' element. That means every newly inserted element is pointed by 'top'.  Whenever we want to remove an element from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its next node in the list.  The next field of the first element must be always NULL.  In above example, the last inserted node is 99 and the first inserted node is 25. The order of elements inserted is 25, 32,50 and 99. 49 http://www.simplycs.in http://www.sitcoe.org.in
  • 50. How to Implement Stack using Linked List Operations To implement stack using linked list, we need to set the following things before implementing actual operations.  Step 1: Include all the header files which are used in the program. And declare all the user defined functions.  Step 2: Define a 'Node' structure with two members data and next.  Step 3: Define a Node pointer 'top' and set it to NULL.  Step 4: Implement the main method by displaying Menu with list of operations and make suitable function calls in the main method. 50 http://www.simplycs.in http://www.sitcoe.org.in
  • 51. How to Implement Stack using Linked List push(value) - Inserting an element into the Stack We can use the following steps to insert a new node into the stack...  Step 1: Create a newNode with given value.  Step 2: Check whether stack is Empty (top == NULL)  Step 3: If it is Empty, then set newNode → next = NULL.  Step 4: If it is Not Empty, then set newNode → next = top.  Step 5: Finally, set top = newNode. pop() - Deleting an Element from a Stack We can use the following steps to delete a node from the stack...  Step 1: Check whether stack is Empty (top == NULL).  Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the function  Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.  Step 4: Then set 'top = top → next'.  Step 7: Finally, delete 'temp' (free(temp)). 51 http://www.simplycs.in http://www.sitcoe.org.in
  • 52. How to Implement Stack using Linked List display() - Displaying stack of elements We can use the following steps to display the elements (nodes) of a stack...  Step 1: Check whether stack is Empty (top == NULL).  Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.  Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.  Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until temp reaches to the first node in the stack (temp → next != NULL).  Step 4: Finally! Display 'temp → data ---> NULL'. 52 http://www.simplycs.in http://www.sitcoe.org.in
  • 53. How to Implement Stack using Linked List 53 http://www.simplycs.in http://www.sitcoe.org.in #include<conio.h> #include<stdio.h> struct Node { int data; struct Node *next; }*top = NULL; void push(int); void pop(); void display(); void main() { int choice, value; clrscr(); printf("n:: Stack using Linked List ::n"); while(1){ printf("n****** MENU ******n"); printf("1. Pushn2. Popn3. Displayn4. Exitn"); printf("Enter your choice: "); scanf("%d",&choice); switch(choice){ case 1: printf("Enter the value to be insert: "); scanf("%d", &value); push(value); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("nWrong selection!!! Please try again!!!n"); } } }
  • 54. How to Implement Stack using Linked List 54 http://www.simplycs.in http://www.sitcoe.org.in void push(int value) { struct Node *p; p = (struct Node*)malloc(sizeof(struct Node)); p->data = value; if(top == NULL) p->next = NULL; else p->next = top; top = p; printf("nInsertion is Success!!!n"); } void pop() { if(top == NULL) { printf("nStack is Empty!!!n"); } else { struct Node *temp = top; printf("nDeleted element: %d", temp->data); top = temp->next; free(temp); } }
  • 55. void display() { if(top == NULL) printf("nStack is Empty!!!n"); else{ struct Node *p = top; while(p->next != NULL){ printf("%d--->",p->data); p = p-> next; } printf("%d--->NULL",p->data); } 55
  • 56. How to Implement Queue using Linked List  The major problem with the queue implemented using array is, It will work for only fixed number of data.  That means, the amount of data must be specified in the beginning itself.  Queue using array is not suitable when we don't know the size of data which we are going to use. A queue data structure can be implemented using linked list data structure.  The queue which is implemented using linked list can work for unlimited number of values. That means, queue using linked list can work for variable size of data (No need to fix the size at beginning of the implementation).  The Queue implemented using linked list can organize as many data values as we want. In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is always pointed by 'front'.  In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted node is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50. 56 http://www.simplycs.in http://www.sitcoe.org.in
  • 57. How to Implement Queue using Linked List Operations To implement queue using linked list, we need to set the following things before implementing actual operations.  Step 1: Include all the header files which are used in the program. And declare all the user defined functions.  Step 2: Define a 'Node' structure with two members data and next.  Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.  Step 4: Implement the main method by displaying Menu of list of operations and make suitable function calls in the main method to perform user selected operation. enQueue(value) - Inserting an element into the Queue  We can use the following steps to insert a new node into the queue...  Step 1: Create a newNode with given value and set 'newNode → next' to NULL.  Step 2: Check whether queue is Empty (rear == NULL)  Step 3: If it is Empty then, set front = newNode and rear = newNode.  Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode. 57 http://www.simplycs.in http://www.sitcoe.org.in
  • 58. How to Implement Queue using Linked List deQueue() - Deleting an Element from Queue We can use the following steps to delete a node from the queue...  Step 1: Check whether queue is Empty (front == NULL).  Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from the function  Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.  Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)). display() - Displaying the elements of Queue We can use the following steps to display the elements (nodes) of a queue...  Step 1: Check whether queue is Empty (front == NULL).  Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.  Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.  Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until 'temp' reaches to 'rear' (temp → next != NULL).  Step 4: Finally! Display 'temp → data ---> NULL'. Do Program58 http://www.simplycs.in http://www.sitcoe.org.in