SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
Linked List (Introduction)
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous
location; the elements are linked using pointers.
WhyLinked List?
Arrays can be used to store linear data of similar types, but arrays have the 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 the room has to be created for the new elements
and to create room existing elements have to be shifted.
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.
Advantagesover arrays
1) Dynamic size
2) Ease of insertion/deletion
Drawbacks:
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 efficiently with its default implementation. Read about it here.
2) Extra memory space for a pointer is required with each element of the list.
3) Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case
of linked lists.
Representation:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list
is empty, then the value of the head is NULL.
Each node in a list consists of at least two parts:
1) data
2) Pointer (Or Reference) to the next node
In C, we can represent a node using structures. Below is an example of a linked list node with integer data.
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
/
// A simple C program for traversal of a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* next;
};
 
// This function prints contents of linked list starting from
// the given node
void printList(struct Node* n)
{
    while (n != NULL) {
        printf(" %d ", n->data);
        n = n->next;
         }
}
 
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 second
 
    second->data = 2; // assign data to second node
    second->next = third;
 
    third->data = 3; // assign data to third node
    third->next = NULL;
 
    printList(head);
 
    return 0;
    
    Output: 
 1  2  3
Difference between Singly linked list and
Doubly linked list
IntroductiontoSinglylinked list : A singly linked list is a set of nodes where each node has two fields ‘data’ and ‘link’.
The ‘data’ field stores actual piece of information and ‘link’ field is used to point to next node. Basically the ‘link’ field
stores the address of the next node.
IntroductiontoDoublylinked list : A DoublyLinked List (DLL) contains an extra pointer, typically called previous
pointer, together with next pointer and data which are there in singly linked list.
Singlylinked list vsDoublylinked list
Two-Way Header Lists:
The advantages of a two-way list a circular header list may be combined into a two-way circular header list as . The list is
circular because the two end nodes point back to the header node.Observe that such a two-way list requires only one list
pointer variable START, which points to the header node. This is because the two pointers in the header node point to the
two ends of the list.
What is a two way list?A two way list is a linear collection of data elements, called nodes, where each node N is divided into
three parts:- information field, Forward link- which points to the next node and Backward link-which points to the previous
node.
Two Way List
Singly linked list
(SLL)
Doubly linked list
(DLL)
D
SLL nodes
contains 2
field -data
field and next
link field.
DLL nodes
contains 3
fields -data
field, a
previous link
field and a
next link field.
In SLL, the
traversal can
be done using
the next node
link only. Thus
traversal is
possible in
one direction
only.
In DLL, the
traversal can
be done using
the previous
node link or
the next node
link. Thus
traversal is
possible in
both
directions
(forward and
backward).
The SLL
occupies less
memory than
DLL as it has
only 2 fields.
The DLL
occupies
more memory
than SLL as it
has 3 fields.
Complexity of
insertion and
deletion at a
given position
is O(n).
Complexity of
insertion and
deletion at a
given position
is O(1).
1
2
3
4
5
Doubly linked listDoubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well
as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts: node data, pointer to
the next node in sequence (next pointer) , pointer to the previous node (previous pointer). A sample node in a doubly
linked list is shown in the figure.
A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in the following image.
In C, structure of a node in doubly linked list can be given as :
struct node  
{  
    struct node *prev;  
    int data;  
    struct node *next;  
}   
The prev part of the first node and the next part of the last node will always contain null indicating end in each direction.
In a singly linked list, we could traverse only in one direction, because each node contains address of the next node and it
doesn't have any record of its previous nodes. However, doubly linked list overcome this limitation of singly linked list.
Due to the fact that, each node of the list contains the address of its previous node, we can find all the details about the
previous node as well by using the previous address stored inside the previous part of each node.
Operations on doubly linked list
NodeCreation
1.
2.
3.
4.
5.
6.
7.
struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node *head;
garbagecollectionand compactionindata structures
Garbagecollection: Marking unreachable memory blocks (garbage) as free. Compaction: Moving reachable memory
blocks close together, so that there are not free memory blocks between them. The garbagecollector will release any
garbage memory, without any need to actively free memory like C programmers do.
GarbageCollection. In computer science, garbagecollection is a type of memory management. It automatically cleans
up unused objects and pointers in memory, allowing the resources to be used again. Garbagecollection may also be
done at compile-time, when a program's source code is compiled into an executable program.
Waste compaction is the process of compacting waste, reducing it in size. Garbage compactors and waste collection
vehicles compress waste so that more of it can be stored in the same space. Waste is compacted again, more thoroughly, at
the landfill to conserve valuable airspace and to extend the landfill's life span.
What is garbage data?
Garbage is data that a software program stores in computer RAM (memory) that is no longer needed by that program.
This garbage data is often removed through a process called garbage collection to free up memory space.

Contenu connexe

Tendances

Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and searchEstiak Khan
 
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
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm KristinaBorooah
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queuesRamzi Alqrainy
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListManishPrajapati78
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked ListReazul Islam
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked listsAbdullah Al-hazmy
 

Tendances (20)

Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and search
 
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 in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
 
Linked List
Linked ListLinked List
Linked List
 
Singly link list
Singly link listSingly link list
Singly link list
 
Link list
Link listLink list
Link list
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
 
Link List
Link ListLink List
Link List
 
linked list
linked listlinked list
linked list
 
Link list
Link listLink list
Link list
 
Linked Lists
Linked ListsLinked Lists
Linked Lists
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Linked list
Linked listLinked list
Linked list
 
Linked lists
Linked listsLinked lists
Linked lists
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
 
single linked list
single linked listsingle linked list
single linked list
 

Similaire à Linked list (introduction) 1

1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptxssuserd2f031
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfraji175286
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked listSumathi Kv
 
Linked List Basics
Linked List BasicsLinked List Basics
Linked List BasicsKaustavRoy40
 
02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseoJinTaek Seo
 
2 marks- DS using python
2 marks- DS using python2 marks- DS using python
2 marks- DS using pythonLavanyaJ28
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfKamranAli649587
 
DLL DATA STRUCT.pptx
DLL DATA STRUCT.pptxDLL DATA STRUCT.pptx
DLL DATA STRUCT.pptxMuwaffiqa
 
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
 
Data Structures(Part 1)
Data Structures(Part 1)Data Structures(Part 1)
Data Structures(Part 1)SURBHI SAROHA
 

Similaire à Linked list (introduction) 1 (20)

1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
 
Linked List
Linked ListLinked List
Linked List
 
Linked List
Linked ListLinked List
Linked List
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdf
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
 
Link list
Link listLink list
Link list
 
Linked List Basics
Linked List BasicsLinked List Basics
Linked List Basics
 
Linked list (1).pptx
Linked list (1).pptxLinked list (1).pptx
Linked list (1).pptx
 
Linked list
Linked listLinked list
Linked list
 
02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo
 
2 marks- DS using python
2 marks- DS using python2 marks- DS using python
2 marks- DS using python
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdf
 
DLL DATA STRUCT.pptx
DLL DATA STRUCT.pptxDLL DATA STRUCT.pptx
DLL DATA STRUCT.pptx
 
Data structure
 Data structure Data structure
Data structure
 
Linkedlists
LinkedlistsLinkedlists
Linkedlists
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptx
 
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
 
Data Structures(Part 1)
Data Structures(Part 1)Data Structures(Part 1)
Data Structures(Part 1)
 
Link list
Link listLink list
Link list
 

Dernier

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Dernier (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Linked list (introduction) 1

  • 1. Linked List (Introduction) Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. WhyLinked List? Arrays can be used to store linear data of similar types, but arrays have the 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 the room has to be created for the new elements and to create room existing elements have to be shifted. 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. Advantagesover arrays 1) Dynamic size 2) Ease of insertion/deletion Drawbacks: 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 efficiently with its default implementation. Read about it here. 2) Extra memory space for a pointer is required with each element of the list. 3) Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists. Representation: A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts: 1) data 2) Pointer (Or Reference) to the next node In C, we can represent a node using structures. Below is an example of a linked list node with integer data.
  • 2. // A linked list node struct Node {     int data;     struct Node* next; }; / // A simple C program for traversal of a linked list #include <stdio.h> #include <stdlib.h> struct Node {     int data;     struct Node* next; };   // This function prints contents of linked list starting from // the given node void printList(struct Node* n) {     while (n != NULL) {         printf(" %d ", n->data);         n = n->next;          } }   int main() {     struct Node* head = NULL;     struct Node* second = NULL;     struct Node* third = NULL;       // allocate 3 nodes in the heap
  • 3.     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 second       second->data = 2; // assign data to second node     second->next = third;       third->data = 3; // assign data to third node     third->next = NULL;       printList(head);       return 0;          Output:   1  2  3 Difference between Singly linked list and Doubly linked list IntroductiontoSinglylinked list : A singly linked list is a set of nodes where each node has two fields ‘data’ and ‘link’. The ‘data’ field stores actual piece of information and ‘link’ field is used to point to next node. Basically the ‘link’ field stores the address of the next node. IntroductiontoDoublylinked list : A DoublyLinked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
  • 4. Singlylinked list vsDoublylinked list Two-Way Header Lists: The advantages of a two-way list a circular header list may be combined into a two-way circular header list as . The list is circular because the two end nodes point back to the header node.Observe that such a two-way list requires only one list pointer variable START, which points to the header node. This is because the two pointers in the header node point to the two ends of the list. What is a two way list?A two way list is a linear collection of data elements, called nodes, where each node N is divided into three parts:- information field, Forward link- which points to the next node and Backward link-which points to the previous node. Two Way List Singly linked list (SLL) Doubly linked list (DLL) D SLL nodes contains 2 field -data field and next link field. DLL nodes contains 3 fields -data field, a previous link field and a next link field. In SLL, the traversal can be done using the next node link only. Thus traversal is possible in one direction only. In DLL, the traversal can be done using the previous node link or the next node link. Thus traversal is possible in both directions (forward and backward). The SLL occupies less memory than DLL as it has only 2 fields. The DLL occupies more memory than SLL as it has 3 fields. Complexity of insertion and deletion at a given position is O(n). Complexity of insertion and deletion at a given position is O(1). 1 2 3 4 5
  • 5. Doubly linked listDoubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts: node data, pointer to the next node in sequence (next pointer) , pointer to the previous node (previous pointer). A sample node in a doubly linked list is shown in the figure. A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in the following image. In C, structure of a node in doubly linked list can be given as : struct node   {       struct node *prev;       int data;       struct node *next;   }    The prev part of the first node and the next part of the last node will always contain null indicating end in each direction. In a singly linked list, we could traverse only in one direction, because each node contains address of the next node and it doesn't have any record of its previous nodes. However, doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node of the list contains the address of its previous node, we can find all the details about the previous node as well by using the previous address stored inside the previous part of each node. Operations on doubly linked list NodeCreation 1. 2. 3. 4. 5. 6. 7. struct node { struct node *prev; int data; struct node *next; }; struct node *head; garbagecollectionand compactionindata structures Garbagecollection: Marking unreachable memory blocks (garbage) as free. Compaction: Moving reachable memory blocks close together, so that there are not free memory blocks between them. The garbagecollector will release any garbage memory, without any need to actively free memory like C programmers do. GarbageCollection. In computer science, garbagecollection is a type of memory management. It automatically cleans up unused objects and pointers in memory, allowing the resources to be used again. Garbagecollection may also be done at compile-time, when a program's source code is compiled into an executable program.
  • 6. Waste compaction is the process of compacting waste, reducing it in size. Garbage compactors and waste collection vehicles compress waste so that more of it can be stored in the same space. Waste is compacted again, more thoroughly, at the landfill to conserve valuable airspace and to extend the landfill's life span. What is garbage data? Garbage is data that a software program stores in computer RAM (memory) that is no longer needed by that program. This garbage data is often removed through a process called garbage collection to free up memory space.