SlideShare a Scribd company logo
1 of 31
Linked List
Spring 2012 Programming and Data Structure 1
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.
Spring 2012 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.
Spring 2012 Programming and Data Structure 3
Illustration: Insertion
Spring 2012 Programming and Data Structure 4
A
A
Item to be
inserted
X
X
A B C
B C
curr
tmp
Pseudo-code for insertion
Spring 2012 Programming and Data Structure 5
typedef struct nd {
struct item data;
struct nd * next;
} node;
void insert(node *curr)
{
node * tmp;
tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Illustration: Deletion
Spring 2012 Programming and Data Structure 6
A B
A B C
C
Item to be deleted
curr
tmp
Pseudo-code for deletion
Spring 2012 Programming and Data Structure 7
typedef struct nd {
struct item data;
struct nd * next;
} node;
void delete(node *curr)
{
node * tmp;
tmp=curr->next;
curr->next=tmp->next;
free(tmp);
}
In essence ...
• 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.
Spring 2012 Programming and Data Structure 8
Array versus Linked Lists
• 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.
Spring 2012 Programming and Data Structure 9
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.
Spring 2012 Programming and Data Structure 10
A B C
head
– Circular linked list
• The pointer from the last element in the list points back
to the first element.
Spring 2012 Programming and Data Structure 11
A B C
head
– 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, head and tail.
Spring 2012 Programming and Data Structure 12
A B C
head tail
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
Spring 2012 Programming and Data Structure 13
List is an Abstract Data Type
• What is an abstract data type?
– It is a data type defined by the user.
– Typically more complex than simple data types like
int, float, etc.
• Why abstract?
– Because details of the implementation are hidden.
– When you do some operation on the list, say insert
an element, you just call a function.
– Details of how the list is implemented or how the
insert function is written is no longer required.
Spring 2012 Programming and Data Structure 14
Conceptual Idea
Spring 2012 Programming and Data Structure 15
List
implementation
and the
related functions
Insert
Delete
Traverse
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;
};
/* A user-defined data type called “node” */
typedef struct stud node;
node *head;
Spring 2012 Programming and Data Structure 16
Creating a List
Spring 2012 Programming and Data Structure 17
How to begin?
• To start with, we have to create a node (the
first node), and make head point to it.
head = (node *)
malloc(sizeof(node));
Spring 2012 Programming and Data Structure 18
head
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.
Spring 2012 Programming and Data Structure 19
A B C
head
node *create_list()
{
int k, n;
node *p, *head;
printf ("n How many elements to enter?");
scanf ("%d", &n);
for (k=0; k<n; k++)
{
if (k == 0) {
head = (node *) malloc(sizeof(node));
p = head;
}
else {
p->next = (node *) malloc(sizeof(node));
p = p->next;
}
scanf ("%d %s %d", &p->roll, p->name, &p->age);
}
p->next = NULL;
return (head);
}
Spring 2012 Programming and Data Structure 20
• To be called from main() function as:
node *head;
………
head = create_list();
Spring 2012 Programming and Data Structure 21
Traversing the List
Spring 2012 Programming and Data Structure 22
What is to be done?
• Once the linked list has been constructed and
head 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.
Spring 2012 Programming and Data Structure 23
void display (node *head)
{
int count = 1;
node *p;
p = head;
while (p != NULL)
{
printf ("nNode %d: %d %s %d", count,
p->roll, p->name, p->age);
count++;
p = p->next;
}
printf ("n");
}
Spring 2012 Programming and Data Structure 24
• To be called from main() function as:
node *head;
………
display (head);
Spring 2012 Programming and Data Structure 25
Inserting a Node in a List
Spring 2012 Programming and Data Structure 26
How to do?
• The problem is to insert a node before a
specified node.
– Specified means some value is given for the node
(called key).
– In this example, we consider it to be roll.
• Convention followed:
– If the value of roll is given as negative, the node
will be inserted at the end of the list.
Spring 2012 Programming and Data Structure 27
Contd.
• When a node is added at the beginning,
– Only one next pointer needs to be modified.
• head 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.
Spring 2012 Programming and Data Structure 28
Spring 2012 Programming and Data Structure 29
void insert (node **head)
{
int k = 0, rno;
node *p, *q, *new;
new = (node *) malloc(sizeof(node));
printf ("nData to be inserted: ");
scanf ("%d %s %d", &new->roll, new->name, &new->age);
printf ("nInsert before roll (-ve for end):");
scanf ("%d", &rno);
p = *head;
if (p->roll == rno) /* At the beginning */
{
new->next = p;
*head = new;
}
Spring 2012 Programming and Data Structure 30
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
if (p == NULL) /* At the end */
{
q->next = new;
new->next = NULL;
}
else if (p->roll == rno)
/* In the middle */
{
q->next = new;
new->next = p;
}
}
}
The pointers
q and p
always point
to consecutive
nodes.
• To be called from main() function as:
node *head;
………
insert (&head);
Spring 2012 Programming and Data Structure 31

More Related Content

Similar to linkedlist.ppt

Unit 1 linked list
Unit 1 linked listUnit 1 linked list
Unit 1 linked listLavanyaJ28
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked ListThenmozhiK5
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structuresGlobalidiots
 
Circular linked list
Circular linked listCircular linked list
Circular linked listdchuynh
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked ListsJ.T.A.JONES
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocationkiran Patel
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptxmsohail37
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTbinakasehun2026
 

Similar to linkedlist.ppt (20)

linkedlist (1).ppt
linkedlist (1).pptlinkedlist (1).ppt
linkedlist (1).ppt
 
Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
Unit 1 linked list
Unit 1 linked listUnit 1 linked list
Unit 1 linked list
 
Data structures
Data structuresData structures
Data structures
 
Data structure
 Data structure Data structure
Data structure
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
Linked list
Linked listLinked list
Linked list
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked Lists
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptx
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Linked list
Linked listLinked list
Linked list
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LIST
 

Recently uploaded

Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfAnubhavMangla3
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)Wonjun Hwang
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 

Recently uploaded (20)

Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 

linkedlist.ppt

  • 1. Linked List Spring 2012 Programming and Data Structure 1
  • 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. Spring 2012 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. Spring 2012 Programming and Data Structure 3
  • 4. Illustration: Insertion Spring 2012 Programming and Data Structure 4 A A Item to be inserted X X A B C B C curr tmp
  • 5. Pseudo-code for insertion Spring 2012 Programming and Data Structure 5 typedef struct nd { struct item data; struct nd * next; } node; void insert(node *curr) { node * tmp; tmp=(node *) malloc(sizeof(node)); tmp->next=curr->next; curr->next=tmp; }
  • 6. Illustration: Deletion Spring 2012 Programming and Data Structure 6 A B A B C C Item to be deleted curr tmp
  • 7. Pseudo-code for deletion Spring 2012 Programming and Data Structure 7 typedef struct nd { struct item data; struct nd * next; } node; void delete(node *curr) { node * tmp; tmp=curr->next; curr->next=tmp->next; free(tmp); }
  • 8. In essence ... • 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. Spring 2012 Programming and Data Structure 8
  • 9. Array versus Linked Lists • 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. Spring 2012 Programming and Data Structure 9
  • 10. 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. Spring 2012 Programming and Data Structure 10 A B C head
  • 11. – Circular linked list • The pointer from the last element in the list points back to the first element. Spring 2012 Programming and Data Structure 11 A B C head
  • 12. – 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, head and tail. Spring 2012 Programming and Data Structure 12 A B C head tail
  • 13. 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 Spring 2012 Programming and Data Structure 13
  • 14. List is an Abstract Data Type • What is an abstract data type? – It is a data type defined by the user. – Typically more complex than simple data types like int, float, etc. • Why abstract? – Because details of the implementation are hidden. – When you do some operation on the list, say insert an element, you just call a function. – Details of how the list is implemented or how the insert function is written is no longer required. Spring 2012 Programming and Data Structure 14
  • 15. Conceptual Idea Spring 2012 Programming and Data Structure 15 List implementation and the related functions Insert Delete Traverse
  • 16. 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; }; /* A user-defined data type called “node” */ typedef struct stud node; node *head; Spring 2012 Programming and Data Structure 16
  • 17. Creating a List Spring 2012 Programming and Data Structure 17
  • 18. How to begin? • To start with, we have to create a node (the first node), and make head point to it. head = (node *) malloc(sizeof(node)); Spring 2012 Programming and Data Structure 18 head age name roll next
  • 19. 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. Spring 2012 Programming and Data Structure 19 A B C head
  • 20. node *create_list() { int k, n; node *p, *head; printf ("n How many elements to enter?"); scanf ("%d", &n); for (k=0; k<n; k++) { if (k == 0) { head = (node *) malloc(sizeof(node)); p = head; } else { p->next = (node *) malloc(sizeof(node)); p = p->next; } scanf ("%d %s %d", &p->roll, p->name, &p->age); } p->next = NULL; return (head); } Spring 2012 Programming and Data Structure 20
  • 21. • To be called from main() function as: node *head; ……… head = create_list(); Spring 2012 Programming and Data Structure 21
  • 22. Traversing the List Spring 2012 Programming and Data Structure 22
  • 23. What is to be done? • Once the linked list has been constructed and head 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. Spring 2012 Programming and Data Structure 23
  • 24. void display (node *head) { int count = 1; node *p; p = head; while (p != NULL) { printf ("nNode %d: %d %s %d", count, p->roll, p->name, p->age); count++; p = p->next; } printf ("n"); } Spring 2012 Programming and Data Structure 24
  • 25. • To be called from main() function as: node *head; ……… display (head); Spring 2012 Programming and Data Structure 25
  • 26. Inserting a Node in a List Spring 2012 Programming and Data Structure 26
  • 27. How to do? • The problem is to insert a node before a specified node. – Specified means some value is given for the node (called key). – In this example, we consider it to be roll. • Convention followed: – If the value of roll is given as negative, the node will be inserted at the end of the list. Spring 2012 Programming and Data Structure 27
  • 28. Contd. • When a node is added at the beginning, – Only one next pointer needs to be modified. • head 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. Spring 2012 Programming and Data Structure 28
  • 29. Spring 2012 Programming and Data Structure 29 void insert (node **head) { int k = 0, rno; node *p, *q, *new; new = (node *) malloc(sizeof(node)); printf ("nData to be inserted: "); scanf ("%d %s %d", &new->roll, new->name, &new->age); printf ("nInsert before roll (-ve for end):"); scanf ("%d", &rno); p = *head; if (p->roll == rno) /* At the beginning */ { new->next = p; *head = new; }
  • 30. Spring 2012 Programming and Data Structure 30 else { while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* At the end */ { q->next = new; new->next = NULL; } else if (p->roll == rno) /* In the middle */ { q->next = new; new->next = p; } } } The pointers q and p always point to consecutive nodes.
  • 31. • To be called from main() function as: node *head; ……… insert (&head); Spring 2012 Programming and Data Structure 31