SlideShare a Scribd company logo
LNCT BHOPAL
DEPARTMENT OF CSE
LINKED LIST
A B C
head
Introduction
• A linked list is a data structure which can change
during execution.
– Successive elements are connected by pointers.
– Last element points to NULL.
– It can grow or shrink in size during execution of a
program.
– It can be made just as long as required.
– It does not waste memory space.
Programming and Data Structure 2
A B C
head
• Keeping track of a linked list:
– Must know the pointer to the first element of the
list (called start, head, etc.).
• Linked lists provide flexibility in allowing the
items to be rearranged efficiently.
– Insert an element.
– Delete an element.
Programming and Data Structure 3
• Arrays are suitable for:
– Inserting/deleting an element at the end.
– Randomly accessing any element.
– Searching the list for a particular value.
• Linked lists are suitable for:
– Inserting an element.
– Deleting an element.
– Applications where sequential access is required.
– In situations where the number of elements cannot
be predicted beforehand.
Programming and Data Structure 4
Array versus Linked Lists
Types of Lists
• Depending on the way in which the links are
used to maintain adjacency, several different
types of linked lists are possible.
– Linear singly-linked list (or simply linear list)
• One we have discussed so far.
Programming and Data Structure 5
A B C
Start
– Circular linked list
• The pointer from the last element in the list points back
to the first element.
Programming and Data Structure 6
A B C
start
– Doubly linked list
• Pointers exist between adjacent nodes in both
directions.
• The list can be traversed either forward or backward.
• Usually two pointers are maintained to keep track of
the list, start and last.
Programming and Data Structure 7
A B C
start
Basic Operations on a List
• Creating a list
• Traversing the list
• Inserting an item in the list
• Deleting an item from the list
• Concatenating two lists into one
Programming and Data Structure 8
• For insertion:
– A record is created holding the new item.
– The next pointer of the new record is set to link it to
the item which is to follow it in the list.
– The next pointer of the item which is to precede it
must be modified to point to the new item.
• For deletion:
– The next pointer of the item immediately preceding
the one to be deleted is altered, and made to point
to the item following the deleted item.
Programming and Data Structure 9
Illustration: Insertion
Programming and Data Structure 10
A
A
Item to be
inserted
X
X
A B C
B C
start
tmp X
start
tmp
Pseudo-code for insertion
Programming and Data Structure 11
struct node
{
int data;
struct node * next;
} ;
struct node *start;
void insert()
{
struct node * tmp;
tmp=new node;
tmp->next=start->next;
start->next=tmp;
}
Illustration: Deletion
Programming and Data Structure 12
A B
A B C
C
Item to be deleted
start
tmp
start
Pseudo-code for deletion
Spring 2012 Programming and Data Structure 13
struct node
{
int data;
struct node * next;
};
struct node *start;
void delete()
{
struct node * tmp;
tmp=start->next;
start->next=tmp->next;
delete tmp;
}
Example: Working with linked list
• Consider the structure of a node as follows:
struct stud {
int roll;
char name[25];
int age;
struct stud *next;
};
struct stud *start;
Programming and Data Structure 14
How to begin?
To start with, we have to create a node (the first node),
and make start point to it
start=(struct stud*)malloc(sizeof(struct stud));
Or start= new stud;
Programming and Data Structure 15
start
age
name
roll
next
Contd.
• If there are n number of nodes in the initial
linked list:
– Allocate n records, one by one.
– Read in the fields of the records.
– Modify the links of the records so that the chain is
formed.
Programming and Data Structure 16
A B C
start
void create_list()
{
int k, n;
struct node *ptr,*temp, *stat;
cout<<" How many elements to enter?";
cin>>n;
start=new node;
cin>> p->roll >> p->name >> p->age;
ptr=start;
while(n>1)
{
temp=new node ;
cin>> p->roll >> p->name >> p->age;
temp->link=NULL;  NULL or '0'
ptr->link=temp;
ptr=temp;
n=n-1;
}
}
Programming and Data Structure 17
• To be called from main() function as:
int main()
{
struct node *start;
create_list();
Return 0;
}
Programming and Data Structure 18
Traversing the List
Programming and Data Structure 19
What is to be done?
• Once the linked list has been constructed and
start points to the first node of the list,
– Follow the pointers.
– Display the contents of the nodes as they are
traversed.
– Stop when the next pointer points to NULL.
Programming and Data Structure 20
void display ()
{
struct node *p;
p = start;
while (p != NULL)
{
cout<< p->roll << p->name << p->age;
p = p->next;
}
}
Programming and Data Structure 21
• To be called from main() function as:
int main()
{
display();
return 0;
}
Programming and Data Structure 22
Inserting a Node in a List
Programming and Data Structure 23
How to do?
we are required to insert a specific node.
Here also three conditions arise:
Insertion at the beginning
Insertion at the end .
Insertion an intermediate node.
Programming and Data Structure 24
• When a node is added at the beginning,
– Only one next pointer needs to be modified.
• start is made to point to the new node.
• New node points to the previously first element.
• When a node is added at the end,
– Two next pointers need to be modified.
• Last node now points to the new node.
• New node points to NULL.
• When a node is added in the middle,
– Two next pointers need to be modified.
• Previous node now points to the new node.
• New node points to the next node.
Programming and Data Structure 25
Programming and Data Structure
Algorithm to insert a node at the beginning
1. PTR=(Node*)malloc(sizeof(node)) or PTR= new node
[check for overflow?]
2. If PTR=NULL then
Print allocation error
Exit
else
3. Set PTR→INFO=data
4. Set PTR→Next=start
5. Set start=PTR
6. Exit
Programming and Data Structure
Algorithm to insert a node at the end
1. Create a new node PTR = new node
If PTR=NULL then [check for overflow?]
Print overflow and exit
else
2. Set PTR→Info=item
3. Set PTR→Next=NULL
4. If start=NULL
5. Set start=PTR
6. Set temp=start
7. Repeat step 8 until (temp→next!=NULL)
8. Set temp=temp→next
9. Set temp→next=PTR
Programming and Data Structure 28
Insertion at beginning
void insertbeg()
{
int data;
struct node *ptr;
ptr = (struct node*) malloc(sizeof(struct node));
c++ language-- ptr=new node;
printf("enter data"); cout<<”enter data”;
scanf ("%d", &data); cin>>data;
ptr->info=data; ptr->info=data;
ptr->next=start; ptr->next=start;
start=ptr; start=ptr;
}
Programming and Data Structure 29
Insertion at End
void insertlast()
{
int data;
struct node *ptr,*temp;
ptr = (struct node*) malloc(sizeof(struct node));
// ptr=new node; in c++
Cout<<"enter data";
Cin>>ptr->info;
ptr->next=NULL;
temp=start; /* travesing operation */
while(temp->link!='0')
{
temp=temp->link;
}
temp->link=ptr;
}
Programming and Data Structure
Insert_location (start, data, LOC)
1 PTR= new node;
If PTR=NULL then //check for overflow
Print overflow and exit
else
2 Set PTR→Info= data
3 If start=NULL then
4 Set start=PTR
5 Set PTR→next=NULL
Programming and Data Structure
Insert_location (start, data, LOC) (Cont..)
6 Initialize the counter(I) and pointers temp
Set I=1 & temp=START
7 Repeat step 8 and 9 until I<LOC
8 Set temp=temp→next
9 Set I=I+1
10 PTR→next=temp→next
11 Set temp→next=PTR
Deleting a node from the list
Programming and Data Structure 32
What is to be done?
• Here also we are required to delete a specified
node.
– Say, the node whose roll field is given.
• Here also three conditions arise:
– Deleting the first node.
– Deleting the last node.
– Deleting an intermediate node.
Programming and Data Structure 33
Programming and Data Structure
Algorithm to Delete a Node from Beginning in Singly Linked List
1 [Check for underflow?]
If start=NULL then
Print linked list empty
Exit
End-if
2 Set PTR=START
3 Set START=PTR→next
4 Print element deleted is PTR→info
5 delete PTR
6 exit
Programming and Data Structure 35
Delete the first node
void deletebeg()
{
struct node *ptr;
ptr=start;
start=ptr->link;
free(ptr);
//delete ptr; /* in c++ language */
}
Programming and Data Structure
Algorithm to Delete a Node from end in Singly Linked List
1 [Check for underflow?]
If start=NULL then
Print linked list empty
Exit
End-if
2 If start→next=NULL then
Set PTR=start
Set start=NULL
Print element deleted is=PTR→info
Free(PTR)
Endif
Programming and Data Structure
Algorithm to Delete a Node from end in Singly Linked
List(cont..)
3 Set PTR=start
4 Repeat steps 5 and 6 while PTR→next!=NULL
5 Set LOC=PTR
6 Set PTR=PTR→next
7 Set LOC→next=NULL
8 delete PTR
Programming and Data Structure
Delete a Node from the specific location in Singly Linked List
Delete_location(START,LOC)
[check for underflow?]
1 If start=NULL then print “underflow”
Exit
2 [initialize the counter I and PTR]
Set I=1 & PTR=START
3 Repeat step 4 to 6 until I<LOC
4 Set temp=PTR
5 Set PTR=PTR→next
6 I=I+1
7 Print “element deleted is” PTR→info
8 Set temp→next=PTR→next
9 delete PTR
10 exit
Programming and Data Structure
Circular Linked List:-
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 link
field at the last node.
A B C
start
Programming and Data Structure
Inserting a node at the beginning
1 PTR= new node [Check for overflow?]
2 If PTR=NULL then
Print overflow & exit
Endif
3 If Start==NULL then
4 Set PTR→info=data
5 Set PTR→next=PTR
6 Set start=PTR
Endif
7Set PTR→info=Item
8Set temp = start
9 Repeat step 10 while (temp→next !=Start)
10 Set temp=temp->next
10 Set temp→next=PTR
11 Set PTR->next= start
12 Set Start=PTR
Programming and Data Structure
Inserting a new node at the end
1 PTR= new node [Check for overflow?]
2 If PTR=NULL then
Print overflow & exit
Endif
3 If Start==NULL then
4 Set PTR→info=data
5 Set PTR→next=PTR
6 Set start=PTR
Endif
7Set PTR→info=Item
8Set temp = start
9 Repeat step 10 while (temp→next !=Start)
10 Set temp=temp->next
10 Set temp→next=PTR
11 Set PTR->next= start
A First-in First-out (FIFO) List
Programming and Data Structure 42
Also called a QUEUE
In Out
A
C B
A
B
A Last-in First-out (LIFO) List
Programming and Data Structure 43
In Out
A
B
C C
B
Also called a
STACK
Last-In-First-Out STACK
Assume:: stack contains integer elements
void push (stack *s, int element);
/* Insert an element in the stack */
int pop (stack *s);
/* Remove and return the top element */
void create (stack *s); /* Create a new stack */
int isempty (stack *s); /* Check if stack is empty */
int isfull (stack *s); /* Check if stack is full */
Programming and Data Structure 44
Programming and Data Structure 45
STACK
push
create
pop
isfull
isempty
Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list
Programming and Data Structure 46
Stack Implementations: Using Array
and Linked List
Programming and Data Structure 47
STACK USING ARRAY
Programming and Data Structure 48
top
top
PUSH
STACK USING ARRAY
Programming and Data Structure 49
top
top
POP
Stack: Linked List Structure
Programming and Data Structure 50
top
PUSH OPERATION
Stack: Linked List Structure
Programming and Data Structure 51
top
POP OPERATION
Basic Idea
• In the array implementation, we would:
– Declare an array of fixed size (which determines the maximum size of
the stack).
– Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.
• In the linked list implementation, we would:
– Maintain the stack as a linked list.
– A pointer variable top points to the start of the list.
– The first element of the linked list is considered as the stack top.
Programming and Data Structure 53
Declaration
#define MAXSIZE 100
int main()
{
int st[MAXSIZE];
int top;
}
struct lifo
{
int value;
struct lifo *next;
};
struct lifo *top;
Programming and Data Structure 54
ARRAY LINKED LIST
Pushing an element into the stack
void push (int element)
{
if (top == (MAXSIZE-1))
{
printf (“n Stack overflow”);
exit(0);
}
else
{
top ++;
st[top] = element;
}
}
Programming and Data Structure 55
ARRAY
void push(int data)
{
if (top == NULL)
{
printf (“n Stack is empty”);
}
else
{
temp =(struct lifo *)malloc(sizeof(struct
lifo));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
Programming and Data Structure 56
LINKED LIST
Popping an element from the stack
int pop ()
{
if (top == -1)
{
printf (“n Stack underflow”);
exit(0);
}
else
{ element=st[top];
Top--;
return (element);
}
}
Programming and Data Structure 57
ARRAY
void pop()
{
temp = top;
if (temp == NULL)
{
printf("n stack is empty");
return;
}
else
temp = top->ptr;
printf("n Popped value : %d",
top->info);
free(top);
top = temp;
}
Programming and Data Structure 58
LINKED LIST
Checking for stack empty
int isempty ()
{
if (top == -1)
return 1;
else
return (0);
}
int isempty ()
{
if (top == NULL)
return (1);
else
return (0);
}
Programming and Data Structure 59
ARRAY LINKED LIST
Checking for stack full
int isfull ()
{
if (top ==
(MAXSIZE–1))
return 1;
else
return (0);
}
• Not required for linked list
implementation.
• In the push() function, we
can check the return value of
malloc().
– If -1, then memory cannot be
allocated.
Programming and Data Structure 60
ARRAY LINKED LIST
Queue Implementation using Linked
List
Programming and Data Structure 61
Basic Idea
• Basic idea:
– Create a linked list to which items would be added
to one end and deleted from the other end.
– Two pointers will be maintained:
• One pointing to the beginning of the list (point from
where elements will be deleted).
• Another pointing to the end of the list (point where
new elements will be inserted).
Programming and Data Structure 62
Front
Rear
DELETION
INSERTION
QUEUE: LINKED LIST STRUCTURE
Programming and Data Structure 63
front rear
ENQUEUE
QUEUE: LINKED LIST STRUCTURE
Spring 2012 Programming and Data Structure 64
front rear
ENQUEUE
QUEUE: LINKED LIST STRUCTURE
Programming and Data Structure 65
front rear
DEQUEUE
Problem With Array Implementation
Programming and Data Structure 66
front rear rear
ENQUEUE
front
DEQUEUE
Effective queuing storage area of array gets reduced.
Use of circular array indexing
0 N
struct node *link;
};
int main()
{
int data;
struct node *p,*next,*temp;
p=new node;
cout<<"enter the data of first node";
cin>>p->info;
next=new node;
cout<<"enter the data of second node";
cin>>next->info;
p->link=next;
next->link='0';
//temp=p;
while(p!='0')
{
cout<<p->info<<" ";
struct node *ptr,*temp;
int data,n;
char ch;
ptr=new node;
cout<<"enter tnr node information ";
cin>>ptr->info;
//ptr->info=data;
ptr->link=NULL;
start=ptr;
next:
cout<<"do u want to any node";
cin>>ch;
if(ch=='y')
/*cout<<"enter how many nodes to be inserted";
cin>>n;
while(n>0)*/
{
temp=new node;

More Related Content

Similar to Linked list introduction and different operation (20)

PPT
Wk11-linkedlist.ppt
duraimurugan alagarsamy
 
PPT
Data Structures 3
Dr.Umadevi V
 
PPTX
Revisiting a data structures in detail with linked list stack and queue
ssuser7319f8
 
PPTX
DS_LinkedList.pptx
msohail37
 
PPTX
Linked lists a
Khuram Shahzad
 
PPT
Unit 1 linked list
LavanyaJ28
 
PPT
linkedlist.ppt
soniya555961
 
PPTX
VCE Unit 02 (1).pptx
skilljiolms
 
PPTX
unit 1.pptx
ssuser7922b8
 
PDF
Data and File Structure Lecture Notes
FellowBuddy.com
 
PDF
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Borraramkumar
 
PPT
Linked list1.ppt
KasthuriKAssistantPr
 
PPT
Unit ii(dsc++)
Durga Devi
 
PPT
DS Unit 2.ppt
JITTAYASHWANTHREDDY
 
PPTX
Linked List.pptx
PoonamPatil120
 
PPT
Algo>ADT list & linked list
Ain-ul-Moiz Khawaja
 
PPTX
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
shesnasuneer
 
PPTX
Data Structures_Linked List
ThenmozhiK5
 
PPTX
Linked List Data structure using C programming and all the detailed informat...
meenaka Rajendran
 
Wk11-linkedlist.ppt
duraimurugan alagarsamy
 
Data Structures 3
Dr.Umadevi V
 
Revisiting a data structures in detail with linked list stack and queue
ssuser7319f8
 
DS_LinkedList.pptx
msohail37
 
Linked lists a
Khuram Shahzad
 
Unit 1 linked list
LavanyaJ28
 
linkedlist.ppt
soniya555961
 
VCE Unit 02 (1).pptx
skilljiolms
 
unit 1.pptx
ssuser7922b8
 
Data and File Structure Lecture Notes
FellowBuddy.com
 
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Borraramkumar
 
Linked list1.ppt
KasthuriKAssistantPr
 
Unit ii(dsc++)
Durga Devi
 
DS Unit 2.ppt
JITTAYASHWANTHREDDY
 
Linked List.pptx
PoonamPatil120
 
Algo>ADT list & linked list
Ain-ul-Moiz Khawaja
 
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
shesnasuneer
 
Data Structures_Linked List
ThenmozhiK5
 
Linked List Data structure using C programming and all the detailed informat...
meenaka Rajendran
 

Recently uploaded (20)

PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Ad

Linked list introduction and different operation

  • 1. LNCT BHOPAL DEPARTMENT OF CSE LINKED LIST A B C head
  • 2. Introduction • A linked list is a data structure which can change during execution. – Successive elements are connected by pointers. – Last element points to NULL. – It can grow or shrink in size during execution of a program. – It can be made just as long as required. – It does not waste memory space. Programming and Data Structure 2 A B C head
  • 3. • Keeping track of a linked list: – Must know the pointer to the first element of the list (called start, head, etc.). • Linked lists provide flexibility in allowing the items to be rearranged efficiently. – Insert an element. – Delete an element. Programming and Data Structure 3
  • 4. • Arrays are suitable for: – Inserting/deleting an element at the end. – Randomly accessing any element. – Searching the list for a particular value. • Linked lists are suitable for: – Inserting an element. – Deleting an element. – Applications where sequential access is required. – In situations where the number of elements cannot be predicted beforehand. Programming and Data Structure 4 Array versus Linked Lists
  • 5. Types of Lists • Depending on the way in which the links are used to maintain adjacency, several different types of linked lists are possible. – Linear singly-linked list (or simply linear list) • One we have discussed so far. Programming and Data Structure 5 A B C Start
  • 6. – Circular linked list • The pointer from the last element in the list points back to the first element. Programming and Data Structure 6 A B C start
  • 7. – Doubly linked list • Pointers exist between adjacent nodes in both directions. • The list can be traversed either forward or backward. • Usually two pointers are maintained to keep track of the list, start and last. Programming and Data Structure 7 A B C start
  • 8. Basic Operations on a List • Creating a list • Traversing the list • Inserting an item in the list • Deleting an item from the list • Concatenating two lists into one Programming and Data Structure 8
  • 9. • For insertion: – A record is created holding the new item. – The next pointer of the new record is set to link it to the item which is to follow it in the list. – The next pointer of the item which is to precede it must be modified to point to the new item. • For deletion: – The next pointer of the item immediately preceding the one to be deleted is altered, and made to point to the item following the deleted item. Programming and Data Structure 9
  • 10. Illustration: Insertion Programming and Data Structure 10 A A Item to be inserted X X A B C B C start tmp X start tmp
  • 11. Pseudo-code for insertion Programming and Data Structure 11 struct node { int data; struct node * next; } ; struct node *start; void insert() { struct node * tmp; tmp=new node; tmp->next=start->next; start->next=tmp; }
  • 12. Illustration: Deletion Programming and Data Structure 12 A B A B C C Item to be deleted start tmp start
  • 13. Pseudo-code for deletion Spring 2012 Programming and Data Structure 13 struct node { int data; struct node * next; }; struct node *start; void delete() { struct node * tmp; tmp=start->next; start->next=tmp->next; delete tmp; }
  • 14. Example: Working with linked list • Consider the structure of a node as follows: struct stud { int roll; char name[25]; int age; struct stud *next; }; struct stud *start; Programming and Data Structure 14
  • 15. How to begin? To start with, we have to create a node (the first node), and make start point to it start=(struct stud*)malloc(sizeof(struct stud)); Or start= new stud; Programming and Data Structure 15 start age name roll next
  • 16. Contd. • If there are n number of nodes in the initial linked list: – Allocate n records, one by one. – Read in the fields of the records. – Modify the links of the records so that the chain is formed. Programming and Data Structure 16 A B C start
  • 17. void create_list() { int k, n; struct node *ptr,*temp, *stat; cout<<" How many elements to enter?"; cin>>n; start=new node; cin>> p->roll >> p->name >> p->age; ptr=start; while(n>1) { temp=new node ; cin>> p->roll >> p->name >> p->age; temp->link=NULL; NULL or '0' ptr->link=temp; ptr=temp; n=n-1; } } Programming and Data Structure 17
  • 18. • To be called from main() function as: int main() { struct node *start; create_list(); Return 0; } Programming and Data Structure 18
  • 19. Traversing the List Programming and Data Structure 19
  • 20. What is to be done? • Once the linked list has been constructed and start points to the first node of the list, – Follow the pointers. – Display the contents of the nodes as they are traversed. – Stop when the next pointer points to NULL. Programming and Data Structure 20
  • 21. void display () { struct node *p; p = start; while (p != NULL) { cout<< p->roll << p->name << p->age; p = p->next; } } Programming and Data Structure 21
  • 22. • To be called from main() function as: int main() { display(); return 0; } Programming and Data Structure 22
  • 23. Inserting a Node in a List Programming and Data Structure 23
  • 24. How to do? we are required to insert a specific node. Here also three conditions arise: Insertion at the beginning Insertion at the end . Insertion an intermediate node. Programming and Data Structure 24
  • 25. • When a node is added at the beginning, – Only one next pointer needs to be modified. • start is made to point to the new node. • New node points to the previously first element. • When a node is added at the end, – Two next pointers need to be modified. • Last node now points to the new node. • New node points to NULL. • When a node is added in the middle, – Two next pointers need to be modified. • Previous node now points to the new node. • New node points to the next node. Programming and Data Structure 25
  • 26. Programming and Data Structure Algorithm to insert a node at the beginning 1. PTR=(Node*)malloc(sizeof(node)) or PTR= new node [check for overflow?] 2. If PTR=NULL then Print allocation error Exit else 3. Set PTR→INFO=data 4. Set PTR→Next=start 5. Set start=PTR 6. Exit
  • 27. Programming and Data Structure Algorithm to insert a node at the end 1. Create a new node PTR = new node If PTR=NULL then [check for overflow?] Print overflow and exit else 2. Set PTR→Info=item 3. Set PTR→Next=NULL 4. If start=NULL 5. Set start=PTR 6. Set temp=start 7. Repeat step 8 until (temp→next!=NULL) 8. Set temp=temp→next 9. Set temp→next=PTR
  • 28. Programming and Data Structure 28 Insertion at beginning void insertbeg() { int data; struct node *ptr; ptr = (struct node*) malloc(sizeof(struct node)); c++ language-- ptr=new node; printf("enter data"); cout<<”enter data”; scanf ("%d", &data); cin>>data; ptr->info=data; ptr->info=data; ptr->next=start; ptr->next=start; start=ptr; start=ptr; }
  • 29. Programming and Data Structure 29 Insertion at End void insertlast() { int data; struct node *ptr,*temp; ptr = (struct node*) malloc(sizeof(struct node)); // ptr=new node; in c++ Cout<<"enter data"; Cin>>ptr->info; ptr->next=NULL; temp=start; /* travesing operation */ while(temp->link!='0') { temp=temp->link; } temp->link=ptr; }
  • 30. Programming and Data Structure Insert_location (start, data, LOC) 1 PTR= new node; If PTR=NULL then //check for overflow Print overflow and exit else 2 Set PTR→Info= data 3 If start=NULL then 4 Set start=PTR 5 Set PTR→next=NULL
  • 31. Programming and Data Structure Insert_location (start, data, LOC) (Cont..) 6 Initialize the counter(I) and pointers temp Set I=1 & temp=START 7 Repeat step 8 and 9 until I<LOC 8 Set temp=temp→next 9 Set I=I+1 10 PTR→next=temp→next 11 Set temp→next=PTR
  • 32. Deleting a node from the list Programming and Data Structure 32
  • 33. What is to be done? • Here also we are required to delete a specified node. – Say, the node whose roll field is given. • Here also three conditions arise: – Deleting the first node. – Deleting the last node. – Deleting an intermediate node. Programming and Data Structure 33
  • 34. Programming and Data Structure Algorithm to Delete a Node from Beginning in Singly Linked List 1 [Check for underflow?] If start=NULL then Print linked list empty Exit End-if 2 Set PTR=START 3 Set START=PTR→next 4 Print element deleted is PTR→info 5 delete PTR 6 exit
  • 35. Programming and Data Structure 35 Delete the first node void deletebeg() { struct node *ptr; ptr=start; start=ptr->link; free(ptr); //delete ptr; /* in c++ language */ }
  • 36. Programming and Data Structure Algorithm to Delete a Node from end in Singly Linked List 1 [Check for underflow?] If start=NULL then Print linked list empty Exit End-if 2 If start→next=NULL then Set PTR=start Set start=NULL Print element deleted is=PTR→info Free(PTR) Endif
  • 37. Programming and Data Structure Algorithm to Delete a Node from end in Singly Linked List(cont..) 3 Set PTR=start 4 Repeat steps 5 and 6 while PTR→next!=NULL 5 Set LOC=PTR 6 Set PTR=PTR→next 7 Set LOC→next=NULL 8 delete PTR
  • 38. Programming and Data Structure Delete a Node from the specific location in Singly Linked List Delete_location(START,LOC) [check for underflow?] 1 If start=NULL then print “underflow” Exit 2 [initialize the counter I and PTR] Set I=1 & PTR=START 3 Repeat step 4 to 6 until I<LOC 4 Set temp=PTR 5 Set PTR=PTR→next 6 I=I+1 7 Print “element deleted is” PTR→info 8 Set temp→next=PTR→next 9 delete PTR 10 exit
  • 39. Programming and Data Structure Circular Linked List:- 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 link field at the last node. A B C start
  • 40. Programming and Data Structure Inserting a node at the beginning 1 PTR= new node [Check for overflow?] 2 If PTR=NULL then Print overflow & exit Endif 3 If Start==NULL then 4 Set PTR→info=data 5 Set PTR→next=PTR 6 Set start=PTR Endif 7Set PTR→info=Item 8Set temp = start 9 Repeat step 10 while (temp→next !=Start) 10 Set temp=temp->next 10 Set temp→next=PTR 11 Set PTR->next= start 12 Set Start=PTR
  • 41. Programming and Data Structure Inserting a new node at the end 1 PTR= new node [Check for overflow?] 2 If PTR=NULL then Print overflow & exit Endif 3 If Start==NULL then 4 Set PTR→info=data 5 Set PTR→next=PTR 6 Set start=PTR Endif 7Set PTR→info=Item 8Set temp = start 9 Repeat step 10 while (temp→next !=Start) 10 Set temp=temp->next 10 Set temp→next=PTR 11 Set PTR->next= start
  • 42. A First-in First-out (FIFO) List Programming and Data Structure 42 Also called a QUEUE In Out A C B A B
  • 43. A Last-in First-out (LIFO) List Programming and Data Structure 43 In Out A B C C B Also called a STACK
  • 44. Last-In-First-Out STACK Assume:: stack contains integer elements void push (stack *s, int element); /* Insert an element in the stack */ int pop (stack *s); /* Remove and return the top element */ void create (stack *s); /* Create a new stack */ int isempty (stack *s); /* Check if stack is empty */ int isfull (stack *s); /* Check if stack is full */ Programming and Data Structure 44
  • 45. Programming and Data Structure 45 STACK push create pop isfull isempty
  • 46. Contd. • We shall look into two different ways of implementing stack: – Using arrays – Using linked list Programming and Data Structure 46
  • 47. Stack Implementations: Using Array and Linked List Programming and Data Structure 47
  • 48. STACK USING ARRAY Programming and Data Structure 48 top top PUSH
  • 49. STACK USING ARRAY Programming and Data Structure 49 top top POP
  • 50. Stack: Linked List Structure Programming and Data Structure 50 top PUSH OPERATION
  • 51. Stack: Linked List Structure Programming and Data Structure 51 top POP OPERATION
  • 52. Basic Idea • In the array implementation, we would: – Declare an array of fixed size (which determines the maximum size of the stack). – Keep a variable which always points to the “top” of the stack. • Contains the array index of the “top” element. • In the linked list implementation, we would: – Maintain the stack as a linked list. – A pointer variable top points to the start of the list. – The first element of the linked list is considered as the stack top. Programming and Data Structure 53
  • 53. Declaration #define MAXSIZE 100 int main() { int st[MAXSIZE]; int top; } struct lifo { int value; struct lifo *next; }; struct lifo *top; Programming and Data Structure 54 ARRAY LINKED LIST
  • 54. Pushing an element into the stack void push (int element) { if (top == (MAXSIZE-1)) { printf (“n Stack overflow”); exit(0); } else { top ++; st[top] = element; } } Programming and Data Structure 55 ARRAY
  • 55. void push(int data) { if (top == NULL) { printf (“n Stack is empty”); } else { temp =(struct lifo *)malloc(sizeof(struct lifo)); temp->ptr = top; temp->info = data; top = temp; } count++; } Programming and Data Structure 56 LINKED LIST
  • 56. Popping an element from the stack int pop () { if (top == -1) { printf (“n Stack underflow”); exit(0); } else { element=st[top]; Top--; return (element); } } Programming and Data Structure 57 ARRAY
  • 57. void pop() { temp = top; if (temp == NULL) { printf("n stack is empty"); return; } else temp = top->ptr; printf("n Popped value : %d", top->info); free(top); top = temp; } Programming and Data Structure 58 LINKED LIST
  • 58. Checking for stack empty int isempty () { if (top == -1) return 1; else return (0); } int isempty () { if (top == NULL) return (1); else return (0); } Programming and Data Structure 59 ARRAY LINKED LIST
  • 59. Checking for stack full int isfull () { if (top == (MAXSIZE–1)) return 1; else return (0); } • Not required for linked list implementation. • In the push() function, we can check the return value of malloc(). – If -1, then memory cannot be allocated. Programming and Data Structure 60 ARRAY LINKED LIST
  • 60. Queue Implementation using Linked List Programming and Data Structure 61
  • 61. Basic Idea • Basic idea: – Create a linked list to which items would be added to one end and deleted from the other end. – Two pointers will be maintained: • One pointing to the beginning of the list (point from where elements will be deleted). • Another pointing to the end of the list (point where new elements will be inserted). Programming and Data Structure 62 Front Rear DELETION INSERTION
  • 62. QUEUE: LINKED LIST STRUCTURE Programming and Data Structure 63 front rear ENQUEUE
  • 63. QUEUE: LINKED LIST STRUCTURE Spring 2012 Programming and Data Structure 64 front rear ENQUEUE
  • 64. QUEUE: LINKED LIST STRUCTURE Programming and Data Structure 65 front rear DEQUEUE
  • 65. Problem With Array Implementation Programming and Data Structure 66 front rear rear ENQUEUE front DEQUEUE Effective queuing storage area of array gets reduced. Use of circular array indexing 0 N
  • 66. struct node *link; }; int main() { int data; struct node *p,*next,*temp; p=new node; cout<<"enter the data of first node"; cin>>p->info; next=new node; cout<<"enter the data of second node"; cin>>next->info; p->link=next; next->link='0'; //temp=p; while(p!='0') { cout<<p->info<<" ";
  • 67. struct node *ptr,*temp; int data,n; char ch; ptr=new node; cout<<"enter tnr node information "; cin>>ptr->info; //ptr->info=data; ptr->link=NULL; start=ptr; next: cout<<"do u want to any node"; cin>>ch; if(ch=='y') /*cout<<"enter how many nodes to be inserted"; cin>>n; while(n>0)*/ { temp=new node;