lecture four of data structures :Linked List-ds.ppt
1. 4. Linked List
1
4.1 Linked List
4.2 Representation of Linked List
4.3 Advantages and Disadvantages
4.4 Operation on Linked List
4.5 Types of Linked List
4.6 Singly Linked List
4.7 Stack Using Linked List
2. 4. Linked List
2
4.8 Queue Using Linked List
4.9 Queue Using Two Stacks
4.10 Polynomials Using Linked List
4.11 Doubly Linked List
4.12 Circular Linked List
4.13 Priority Queues
3. If the memory is allocated for the variable during the
compilation (i.e., before execution) of a program, then
it is fixed and cannot be changed.
For example, an array a[100] is declared with 100
elements, then the allocated memory is fixed and
cannot decrease or increase the size of the array if
required.
So we have to adopt an alternative strategy to allocate
memory only when it is required.
There is a special data structure called linked list that
provides a more flexible storage system and it does not
required the use of arrays.
4.1 Linked List
3
4. A linked list is a linear collection of specially designed
data elements, called nodes, linked to one another by
means of pointers.
Each node is divided into two parts: the first part
contains the information of the element, and the
second part contains the address of the next node in
the linked list.
Address part of the node is also called linked or next
field.
Definition
4
PTR 50 NULL
PTR -> DATA=50
PTR -> Next=NULL
DATA Next
5. Logical Representation for a Linked List
Linked List
5
DATA
START DATA DATA X
Physical Representation for a Linked List
Physical Space
DATA 0x80010
DATA 0x80031
DATA NULL
0x80017
0x80010
0x80031
START =
6. Suppose we want to store a list of integer numbers using
linked list. Then it can be schematically represented as
follows
4.2 Representation of Linked List
6
Start 31
30 32 34 X
33
Linked list representation of integers.
7. The linear linked list can be represented in memory with
the following declaration.
struct Node
{
int DATA; // Instead of “DATA” we also use “Info”
struct Node *Next; //Instead of “Next” we also use “Link”
};
typedef struct Node *NODE;
Representation of Linked List
7
8. Linked list have many advantages and some of
them are:
1. Linked list are dynamic data structure. That is,
they can grow or shrink during the execution
of a program.
2. Efficient memory utilization: In linked list (or
dynamic) representation, memory is not pre-
allocated. Memory is allocated whenever it is
required. And it is deallocated (or removed)
when it is not needed.
4.3. Advantages and Disadvantages
8
9. 3. Insertion and deletion are easier and efficient.
Linked list provides flexibility in inserting a data
item at a specified position and deletion of a data
item from the given position.
4. Many complex applications can be easily carried
out with linked list.
Linked list has following disadvantages
1. More memory: to store an integer number, a node
with integer data and address field is allocated.
That is more memory space is needed.
2. Access to an arbitrary data item is little bit
cumbersome and also time consuming.
Advantages and Disadvantages (Cont.)
9
10. The primitive operations performed on the linked list
are as follows
1. Creation
2. Insertion
3. Deletion
4. Traversing
5. Searching
6. Concatenation
4.4 Operation on Linked List
10
11. Creation operation is used to create a linked list. Once a
linked list is created with one node, insertion operation
can be used to add more elements in a node.
Insertion operation is used to insert a new node at any
specified location in the linked list. A new node may be
inserted.
(a) At the beginning of the linked list
(b) At the end of the linked list
(c) At any specified position in between in a linked list
Deletion operation is used to delete an item (or node)
from the linked list. A node may be deleted from the
(a) Beginning of a linked list
(b) End of a linked list
(c) Specified location of the linked list
Operation on Linked List
11
12. Traversing is the process of going through all the
nodes from one end to another end of a linked list. In
a singly linked list we can visit from left to right,
forward traversing, nodes only. But in doubly linked
list forward and backward traversing is possible.
Concatenation is the process of appending the
second list to the end of the first list. Consider a list A
having n nodes and B with m nodes. Then the
operation concatenation will place the 1st node of B in
the (n+1)th node in A. After concatenation A will
contain (n+m) nodes
Operation on Linked List
12
13. Basically we can divide the linked list into the
following three types in the order in which they
(or node) are arranged.
1. Singly linked list
2. Doubly linked list
3. Circular linked list
4.5 Types of Linked List
13
14. Types of Linked List
14
Singly linked list
Doubly linked list
Circular singly
linked list
Circular doubly
linked list
15. All the nodes in a singly linked list are arranged
sequentially by linking with a pointer.
A singly linked list can grow or shrink, because it
is a dynamic data structure.
Following figure explains the different operations
on a singly linked list.
4.6 Singly Linked List
15
Start 30 X
Create a node with DATA(30)
16. Insert and Delete a Node
16
Delete the 2nd node from the list
Start 40 X
30
Insert a node with DATA(40) at the end
Start 30
10 40 X
Insert a node with DATA(10) at the beginning
Start 40 X
10
18. Suppose START is the first position in linked list.
Let DATA be the element to be inserted in the new
node. POS is the position where the new node is
to be inserted. TEMP is a temporary pointer to
hold the node address.
Algorithm for Inserting a Node
18
19. Insert a Node at the beginning
1. Input DATA to be inserted
2. Create a NewNode
3. NewNode -> DATA = DATA
4. If (SATRT equal to NULL)
(a) NewNode -> Link = NULL
5. Else
(a) NewNode -> Link = START
6. START = NewNode
7. Exit
Algorithm for Inserting a Node
19
20. Insert a Node at the end
1. Input DATA to be inserted
2. Create a NewNode
3. NewNode -> DATA = DATA
4. NewNode -> Next = NULL
8. If (SATRT equal to NULL)
(a) START = NewNode
9. Else
(a) TEMP = START
(b) While (TEMP -> Next not equal to NULL)
(i) TEMP = TEMP -> Next
10. TEMP -> Next = NewNode
11. Exit
Algorithm for Inserting a Node
20
21. Insert a Node at any specified position
1. Input DATA and POS to be inserted
2. Initialize TEMP = START; and k = 0
3. Repeat the step 3 while( k is less than POS)
(a) TEMP = TEMP -> Next
(b) If (TEMP is equal to NULL)
(i) Display “Node in the list less than the position”
(ii) Exit
(c) k = k + 1
4. Create a New Node
5. NewNode -> DATA = DATA
6. NewNode -> Next = TEMP -> Next
7. TEMP -> Next = NewNode
8. Exit
Algorithm for Inserting a Node
21
22. Algorithm for Deleting a Node
22
Start 30
20 33 34 X
Deletion of a Node
Temp
Hold
Node to be deleted(POS=3)
23. Suppose START is the first position in linked list.
Let DATA be the element to be deleted. TEMP,
HOLD is a temporary pointer to hold the node
address.
1. Input the DATA to be deleted
2. if ((START -> DATA) is equal to DATA)
(a) TEMP = START
(b) START = START -> Next
(c) Set free the node TEMP, which is deleted
(d) Exit
Algorithm for Deleting a Node
23
24. 3. HOLD = START
4. while ((HOLD -> Next -> Next) not equal to NULL))
(a) if ((HOLD -> NEXT -> DATA) equal to DATA)
(i) TEMP = HOLD -> Next
(ii) HOLD -> Next = TEMP -> Next
(iii) Set free the node TEMP, which is deleted
(iv) Exit
(b) HOLD = HOLD -> Next
5. if ((HOLD -> next -> DATA) == DATA)
(a) TEMP = HOLD -> Next
(b) Set free the node TEMP, which is deleted
(c) HOLD -> Next = NULL
(d) Exit
6. Disply “DATA not found”
7. Exit
Algorithm for Deleting a Node
24
25. Suppose START is the address of the first node in
the linked list and DATA is the information to be
searched. After searching, if the DATA is found,
POS will contain the corresponding position in the
list.
Algorithm for Searching a Node
25
26. 1. Input the DATA to be searched
2. Initialize TEMP = START; POS =1;
3. Repeat the step 4, 5 and 6 until (TEMP is equal to
NULL)
4. If (TEMP -> DATA is equal to DATA)
(a) Display “The data is found at POS”
(b) Exit
5. TEMP = TEMP -> Next
6. POS = POS+1
7. If (TEMP is equal to NULL)
(a) Display “The data is not found in the list”
8. Exit
Algorithm for Searching a Node
26
27. Suppose START is the address of the first node in
the linked list. Following algorithm will visit all
nodes from the START node to the end.
1. If (START is equal to NULL)
(a) Display “The list is Empty”
(b) Exit
2. Initialize TEMP = START
3. Repeat the step 4 and 5 until (TEMP == NULL )
4. Display “TEMP -> DATA”
5. TEMP = TEMP -> Next
6. Exit
Algorithm for Display All Nodes
27
28. // This program will implement all the operations
// of the singly linked list
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
// Structure declaration for the node
struct node
{
int info;
struct node *link;
}*start;
Singly Linked List Operations-C Program(1)
28
29. // This function will create a new linked list
void Create_List(int data)
{ struct node *q,*tmp;
// Dynamic memory is been allocated for a node
tmp= (struct node*)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=NULL;
if(start==NULL) // If list is empty
start=tmp;
else
{ // Element inserted at the end
q=start;
while(q->link!=NULL)
q=q->link;
q->link=tmp;
}
} // End of create_list()
Singly Linked List Operations-C Program(2)
29
30. // This function will add new element at the beginning of the
linked list
void AddAtBeg(int data)
{
struct node *tmp;
tmp=(struct node*)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=start;
start=tmp;
} // End of addatbeg
Singly Linked List Operations-C Program(3)
30
31. //Following function will add new element at any position
void AddAfter(int data,int pos)
{ struct node *tmp,*q;
int i;
q=start;
// Finding the position to add new element to the linked list
for(i=0;i<pos-1;i++)
{ q=q->link;
if(q==NULL)
{ printf("nn There are less than %d elements",pos);
getch();
return;
}
} // End of for
tmp=(struct node*)malloc(sizeof (struct node));
tmp->link=q->link;
tmp->info=data;
q->link=tmp;
} // End of addafter()
Singly Linked List Operations-C Program(4)
31
32. // Delete any element from the linked list
void Del(int data)
{ struct node *tmp, *q;
if(start->info == data)
{ tmp=start;
start=start->link; // First element deleted
free(tmp); return; }
q=start;
while(q->link->link != NULL)
{ if(q->link->info == data) // Element deleted in between
{ tmp=q->link; q->link=tmp->link;
free(tmp); return; }
q=q->link;
} // End of while
if(q->link->info==data) // Last element deleted
{ tmp=q->link; free(tmp); q->link=NULL; return; }
printf("nnElement %d not found",data);
getch();
} // End of del()
Singly Linked List Operations-C Program(5)
32
33. // This function will display all the element(s) in the linked list
void Display()
{ struct node *q;
if(start == NULL)
{ printf("nnList is empty");
return;
}
q=start;
printf("nnList is:");
while(q!=NULL)
{ printf("%d ", q->info);
q=q->link;
}
printf("n");
getch();
} // End of display()
Singly Linked List Operations-C Program(6)
33
34. // Function to count the number of nodes in the linked list
void Count()
{
struct node *q=start;
int cnt=0;
while(q!=NULL)
{
q=q->link;
cnt++;
}
printf("Number of elements are %dn",cnt);
getch();
} // End of count()
Singly Linked List Operations-C Program(7)
34
35. // This function will reverse the linked list
void Rev()
{ struct node *p1,*p2,*p3;
if(start->link==NULL) // only one element
return;
p1=start;
p2=p1->link;
p3=p2->link;
p1->link=NULL;
p2->link=p1;
while(p3!=NULL)
{ p1=p2; p2=p3; p3=p3->link; p2->link=p1;
}
start=p2;
} // End of rev()
Singly Linked List Operations-C Program(8)
35
36. // Function to search an element from the linked list
void Search(int data)
{ struct node *ptr = start;
int pos = 1;
// searching for an element in the linked list
while(ptr!=NULL)
{ if(ptr->info==data)
{ printf("nnItem %d found at position %d", data, pos);
getch(); return;
}
ptr = ptr->link; pos++;
}
if(ptr == NULL) printf("nnItem %d not found in list",data);
getch();
}
Singly Linked List Operations-C Program(9)
36
37. int main()
{ int choice, n, m, position, i;
start=NULL;
while(1)
{ system("cls");
printf("1. Create Listn");
printf("2. Add at beginningn");
printf("3. Add aftern");
printf("4. Deleten");
printf("5. Displayn");
printf("6. Countn");
printf("7. Reversen");
printf("8. Searchn");
printf("9. Quitn");
Singly Linked List Operations-C Program(10)
37
38. printf("nEnter your choice:");
scanf("%d", &choice);
switch(choice)
{ case 1:
printf("nnHow many nodes you want: ");
scanf("%d",&n);
for(i=0; i<n; i++)
{ printf("nEnter the element:");
scanf("%d", &m);
Create_List(m); }
break;
case 2:
printf("nnEnter the element:");
scanf("%d", &m);
AddAtBeg(m);
break;
Singly Linked List Operations-C Program(11)
38
39. 3:
"nnEnter the element:");
("%d", &m);
"nEnter the position after which this element is inserted:");
("%d", &position);
fter(m, position);
;
4:
t == NULL)
printf("nnList is empty");
nue; }
"nnEnter the element for deletion:");
("%d", &m);
m);
;
Singly Linked List Operations-C Program(12)
39
40. case 5: Display();
break;
case 6: Count();
break;
case 7: Rev();
break;
case 8: printf("nnEnter the element to be searched:");
scanf("%d", &m);
Search(m);
break;
case 9: exit(0);
default: printf ("nnWrong choice");
getch();
} // End of switch
} // End of while
} // End of main()
Singly Linked List Operations-C Program(13)
40
41. In chapter 3, we have discussed what a stack
means and its different operations.
And we have also discussed the implementation
of stack using array, i.e., static memory allocation.
Implementation issues of the stack (Last In First
Out - LIFO) using linked list is illustrated in the
following figure.
4.7 Stack Using Linked List
41
20
30 10 X
TOP
42. Suppose TOP is a pointer, which is pointing
towards the topmost element of the stack. TOP is
NULL when the stack is empty. DATA is the data
item to be pushed.
1. Input the DATA to be pushed
2. Creat a New Node
3. NewNode -> DATA = DATA
4. NewNode -> Next = TOP
5. TOP = NewNode
6. Exit
Algorithm for Push Operation
42
43. Suppose TOP is a pointer, which is pointing towards the
topmost element of the stack. TOP is NULL when the
stack is empty. TEMP is pointer variable to hold any
nodes address. DATA is the information on the node
which is just deleted.
1. if (TOP is equal to NULL)
(a) Display “The stack is empty”
2. Else
(a) TEMP = TOP
(b) Display “The popped element TOP → DATA”
(c) TOP = TOP -> Next
(d) TEMP -> Next = NULL
(e) Free the TEMP node
3. Exit
Algorithm for Pop Operation
43
44. Queue is a First In First Out [FIFO] data structure. In
chapter 4, we have discussed about queues and its
different operations.
And we have also discussed the implementation of
queue using array, i.e., static memory allocation.
Implementation issues of the queue (First In First Out
- FIFO) using linked list is illustrated in the following
figure.
4.8 Queue Using Linked List
44
20
10 30 X
Front
Rear
45. REAR is a pointer in queue where the new
elements are added. FRONT is a pointer, which is
pointing to the queue where the elements are
popped. DATA is an element to be pushed.
1. Input the DATA element to be pushed
2. Create a New Node
3. NewNode -> DATA = DATA
4. NewNode -> Next = NULL
5. If(REAR not equal to NULL)
(a) REAR -> next = NewNode;
6. REAR = NewNode;
7. Exit
Algorithm for Pushing an Element to a Queue
45
46. REAR is a pointer in queue where the new elements are
added. FRONT is a pointer, which is pointing to the
queue where the elements are popped. DATA is an
element popped from the queue.
1. If (FRONT is equal to NULL)
(a) Display “The Queue is empty”
2. Else
(a) Display “The popped element is FRONT → DATA”
(b) If(FRONT is not equal to REAR)
(i) FRONT = FRONT -> Next
(c) Else
(i) FRONT = NULL;
3. Exit
Algorithm for Popping an Element From a Queue
46
47. A queue can be implemented using two stacks.
Suppose STACK1 and STACK2 are the two stacks.
When an element is pushed on to the queue, push
the same on STACK1.
When an element is popped from the queue, pop all
elements of STACK1 and push the same on
STACK2. Then pop the topmost element of STACK2,
which is the first (front) element to be popped from
the queue. Then pop all elements of STACK2 and
push the same on STACK1 for next operation (i.e.,
push or pop).
4.9 Queue Using Two Stacks
47
48. Different operations, such as addition, subtraction,
division and multiplication of polynomials can be
performed using linked list.
In this section, we discuss about polynomial addition
using linked list. Consider two polynomials f(x) and g(x):
f(x) = ax3
+ bx + c
g(x) = mx4
+ nx3
+ ox2
+ px + q
These two polynomials can be added by
h(x) = f(x)+g(x)=mx4
+ (a+n)x3
+ ox2
+ (b+p)x + (c+q)
i.e., adding the constants of the corresponding
polynomials of the same exponentials.
4.10 Polynomials Using Linked List
48
49. polynomials f(x), g(x) and h(x) can be represented
using linked list as follows.
f(x) = ax3
+ bx + c
g(x) = mx4
+ nx3
+ ox2
+ px + q
h(x) = f(x)+g(x)=mx4
+ (a+n)x3
+ ox2
+ (b+p)x + (c+q)
Polynomials Using Linked List
49
Start b
a 3 1 X
c 0
o
n 3 2 p 1
Start m 4 X
q 0
o
a+n 3 2 b+p 1
Start m 4 X
c+q 0
50. A doubly linked list is one in which all nodes are
linked together by multiple links which help in
accessing both the successor (next) and
predecessor (previous) node for any arbitrary
node within the list.
Every nodes in the doubly linked list has three
fields: LeftPointer, RightPointer and DATA.
4.11 Doubly Linked List
50
RPoint
LPoint DATA
NULL 10
Start 20 30 NULL
51. A node in the doubly linked list can be represented
in memory with the following declarations.
struct Node
{
int DATA;
struct Node *Lchild;
struct Node *Rchild;
}
typedef struct Node *NODE;
All the operations performed on singly linked list
can also be performed on doubly linked list.
Representation of Doubly Linked List
51
52. Node to be inserted
Insert a Node at the 2nd Position
52
NULL 10
Start
20
30 NULL
53. Suppose START is the first position in linked list.
Let DATA be the element to be inserted in the new
node. POS is the position where the NewNode is to
be inserted. TEMP is a temporary pointer to hold
the node address.
Algorithm for Inserting a Node
53
54. 1. Input the DATA and POS
2. Initialize TEMP = START; i = 0
3. Repeat the step 4 if (i less than POS-1) and (TEMP is not equal to
NULL)
4. TEMP = TEMP -> Rchild; i = i +1
5. If (TEMP not equal to NULL) and (i equal to POS-1)
(a) Create a New Node
(b) NewNode -> DATA = DATA
(c) NewNode -> Rchild = TEMP -> Rchild
(d) NewNode -> Lchild = TEMP
(e) TEMP -> Rchild -> Lchild = NewNode
(f ) TEMP -> Rchild = New Node
6. Else
(a) Display “Position NOT found”
7. Exit
Algorithm for Inserting a Node
54
56. Suppose START is the address of the first node in
the linked list. Let POS is the position of the node
to be deleted. TEMP is the temporary pointer to
hold the address of the node. After deletion, DATA
will contain the information on the deleted node.
Algorithm for Deleting a Node
56
57. 1. Input the POS
2. Initialize TEMP = START; i = 0
3. Repeat the step 4 if (i less than POS) and (TEMP is not equal to
NULL)
4. TEMP = TEMP -> Rchild; i = i +1
5. If (TEMP not equal to NULL) and (i equal to POS)
(a) TEMP -> Lchild -> Rchild = TEMP -> Rchild
(b) TEMP -> Rchild -> Lchild = TEMP -> Lchild
(c) DATA = TEMP -> DATA
(d) free(TEMP)
6. Else
(a) Display “Position NOT found”
7. Exit
Algorithm for Deleting a Node
57
58. A circular linked list is one, which has no beginning
and no end. A singly linked list can be made a
circular linked list by simply storing the address of the
very first node in the linked field of the last node.
4.12 Circular Linked List
58
Start 20
10 30 50
40
10
Start 20 30
59. Priority Queue is a queue where each element is
assigned a priority. In priority queue, the elements are
deleted and processed by following rules:
1. An element of higher priority is processed before any
element of lower priority.
2. Two elements with the same priority are processed
according to the order in which they were inserted to
the queue.
4.13 Priority Queues
59
Front 12
10 9 17 X
60 30
Priority
Data