SlideShare a Scribd company logo
1 of 36
Linked List - Insertion & Deletion
Prepared by: Afaq Mansoor Khan
BSSE III- Group A
Session 2017-21
IMSciences, Peshawar.
Last Lecture Summary
• Dynamic Memory Allocation
▫ New Operator
▫ Delete Operator
▫ Heap
▫ dot . and -> operators
• Introduction to Linked List
▫ Types
▫ Advantages
▫ Disadvantages
▫ Applications
▫ Difference between Array and Linked List
Objectives Overview
• Insertion in Linked List with following criteria
▫ Start of the list
▫ End of the list
▫ Middle of the list
▫ Anywhere in the list
• Deletion of a node from
▫ The Tail of the List
▫ The Head of the List
▫ A desired location in the list
▫ Delete node with a particular value
Insertion in Linked List
Insertion
A Node in the Linked List can be inserted at:
1. Beginning of the list.
2. End of the list.
3. Middle of the list
4. Anywhere in the list
Insertion at the Beginning - Algorithm
Steps to insert a Node at beginning :
1. Allocate a new node
2. Insert new element
3. Have new node point to old head
4. Update head to point to new node
Implementation
• int LinkedList :: addAtFront(node *n) {
• int i = 0;
• //making the next of the new Node point to Head
• n->next = head;
• //making the new Node as Head
• head = n;
• i++;
• //returning the position where Node is added
• return i;
• }
Insertion at the End - Algorithm
Steps to insert a Node at End:
1. Allocate a new node
2. Insert new element
3. Have new node point to null
4. Have old last node point to new node
5. Update tail to point to new node
Implementation
• int LinkedList :: addAtEnd(node *n) {
• if(head == NULL) { //If list is empty
• head = n; //making the new Node as Head
• n->next = NULL; //making the next pointe of the new Node as Null
• }
• else {
• node *n2 = getLastNode(); //getting the last node
• n2->next = n; } }
• node* LinkedList :: getLastNode() {
• node* ptr = head; //creating a pointer pointing to Head
• //Iterating over the list till the node whose Next pointer points to null
• //Return that node, because that will be the last node.
• while(ptr->next!=NULL) {
• //if Next is not Null, take the pointer one step forward
• ptr = ptr->next; }
• return ptr; }
Insertion at the Middle - Algorithm
Steps to insert a Node at Middle:
1. Allocate a new node
2. Insert new element
3. Go to node that should follow the one to add
4. Have that node point to the new node
5. Have new node point to node next node to the
found node.
Insertion at a Specific Position - Algorithm
Steps to insert a Node at Specified Position:
1. Traverse the Linked list up to position-1 nodes.
2. Once all the position-1 nodes are traversed,
allocate memory and the given data to the new
node.
3. Point the next pointer of the new node to the next
of current node.
4. Point the next pointer of current node to the new
node.
Implementation
• // function to insert a Node at required postion
• void insertPos(Node** current, int pos, int data)
• {
• if (pos < 1 || pos > size + 1)
• cout << "Invalid postion!" << endl;
• else {
• while (pos--) {
• if (pos == 0) {
• Node* temp = getNode(data);
• temp->next = *current;
• *current = temp;
• }
• else
• current = &(*current)->next;
• }
• size++;
• }
• }
Deletion from Linked List
Deletion
A node in the linked list can be Deleted from:
1. The Tail of the List
2. The Head of the List
3. A Desired location in the list
4. Delete node with a particular value
Deletion at the Beginning - Algorithm
Steps:
1. Store Current Start in Another Temporary Pointer
2. Move Start Pointer One position Ahead
3. Delete temp i.e. Previous Starting Node as we have
Updated Version of Start Pointer
Implementation
• Node *removeFirstNode (struct Node* head)
• {
• if (head == NULL)
• return NULL;
•
• // Move the head pointer to the next node
• Node *temp = head;
• head = head->next;
•
• delete temp;
•
• return head;
• }
Deletion at the End - Algorithm
Steps to Delete a Node at End :
1. Step 1: If FIRST = NULL then
Write “Linked List is Empty”
2. Step 2: If FIRST->LINK = NULL then
Return FIRST->INFO
FIRST=NULL
Else
SAVE=FIRST
Repeat while SAVE->LINK ≠ NULL
PRED=SAVE
SAVE=SAVE->LINK
Return SAVE->INFO
PRED->LINK=NULL
3. Step 3: Exit
Implementation
• Node* removeLastNode(struct Node* head)
• {
• if (head == NULL)
• return NULL;
•
• if (head->next == NULL)
• {
• delete head;
• return NULL;
• }
•
• // Find the second last node
• Node* second_last = head;
• while (second_last->next->next != NULL)
• second_last = second_last->next;
•
• // Delete last node
• delete (second_last->next);
•
• // Change next of second last
• second_last->next = NULL;
•
• return head;
• }
Deletion at a Desired Location - Algorithm
Steps:
1. If start =NULL
2. Print”over flow”
3. Return
4. End if
5. Set ptr=start
6. Assign value=start -> info
7. Set start=start -> next(second node becomes the first
node).
8. Release the node pointed by ptr to the memory heap.
9. Exit.
Implementation
• void deleteNode(struct Node **head_ref, int position)
• {
• if (*head_ref == NULL) // If linked list is empty
• return;
• struct Node* temp = *head_ref; // Store head node
•
• if (position == 0) // If head needs to be removed
• {
• *head_ref = temp->next; // Change head
• free(temp); // free old head
• return;
• }
• for (int i=0; temp!=NULL && i<position-1; i++) // Find previous node of the node to be deleted
• temp = temp->next;
• if (temp == NULL || temp->next == NULL) // If position is more than number of Nodes
• return;
•
• // Node temp->next is the node to be deleted
• // Store pointer to the next of node to be deleted
• struct Node *next = temp->next->next;
•
• // Unlink the node from linked list
• free(temp->next); // Free memory
•
• temp->next = next; // Unlink the deleted node from list
• }
Delete Node with a Particular Value - Algorithm
Steps:
1. Store address of head in a double pointer till we
find a non “key” node. This takes care of the 1st
while loop to handle the special case of the head.
2. If a node is not “key” node then store the address
of node->next in pp.
3. If we find a “key” node later on then change pp
(ultimately node->next) to point to current
node->next
Implementation
• void deleteKey(struct Node **head_ref, int key)
• {
• struct Node* temp = *head_ref, *prev; // Store head node
•
•
• while (temp != NULL && temp->data == key) // If head node itself holds the key or multiple occurrences of key
• {
• *head_ref = temp->next; // Changed head
• free(temp); // free old head
• temp = *head_ref; // Change Temp
• }
•
• while (temp != NULL) // Delete occurrences other than head
• {
• // Search for the key to be deleted, keep track of the
• // previous node as we need to change 'prev->next'
• while (temp != NULL && temp->data != key)
• {
• prev = temp;
• temp = temp->next;
• }
•
• if (temp == NULL) return; // If key was not present in linked list
•
• prev->next = temp->next; // Unlink the node from linked list
•
• free(temp); // Free memory
•
• temp = prev->next; //Update Temp for next iteration of outer loop
• }
• }
Summary
• Insertion in Linked List with following criteria
▫ Start of the list
▫ End of the list
▫ Middle of the list
▫ Anywhere in the list
• Deletion of a node from
▫ The Tail of the List
▫ The Head of the List
▫ A desired location in the list
▫ Delete node with a particular value
References
• https://www.studytonight.com/data-
structures/linear-linked-list
• https://www.codelike.in/c/linked-list/
• http://www.c4learn.com/data-structure
• https://www.slideshare.net/swajahatr/linked-list-c
• http://www.thecodegallery.com/DSM/DeleteLast.ph
p
• https://www.slideshare.net/sathasivamr1/team-7-
42605180

More Related Content

What's hot

Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked ListSayantan Sur
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy TutorialAfzal Badshah
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
Application of Data structure
Application of Data structureApplication of Data structure
Application of Data structureDeepika051991
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)Elavarasi K
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Muhammad Hammad Waseem
 
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
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure NUPOORAWSARMOL
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 

What's hot (20)

Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked List
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Application of Data structure
Application of Data structureApplication of Data structure
Application of Data structure
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
single linked list
single linked listsingle linked list
single linked list
 
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 lists
Linked listsLinked lists
Linked lists
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 

Similar to Linked List Insertion & Deletion - Add, Remove Nodes Anywhere

Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxMeghaKulkarni27
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocationkiran Patel
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queuessuser7319f8
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdfsudhirchourasia86
 

Similar to Linked List Insertion & Deletion - Add, Remove Nodes Anywhere (20)

Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Singly linked list
Singly linked listSingly linked list
Singly linked list
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
 
DSModule2.pptx
DSModule2.pptxDSModule2.pptx
DSModule2.pptx
 
LinkedDoublyLists.ppt
LinkedDoublyLists.pptLinkedDoublyLists.ppt
LinkedDoublyLists.ppt
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptx
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queue
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
 
3.linked list
3.linked list3.linked list
3.linked list
 

More from Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingAfaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in PakistanAfaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAfaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An OverviewAfaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design DecisionsAfaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinAfaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - AsteroidsAfaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked ListsAfaq Mansoor Khan
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 

More from Afaq Mansoor Khan (20)

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
 
Quick sort
Quick sortQuick sort
Quick sort
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Binary tree
Binary treeBinary tree
Binary tree
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked Lists
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 

Recently uploaded

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Linked List Insertion & Deletion - Add, Remove Nodes Anywhere

  • 1. Linked List - Insertion & Deletion Prepared by: Afaq Mansoor Khan BSSE III- Group A Session 2017-21 IMSciences, Peshawar.
  • 2. Last Lecture Summary • Dynamic Memory Allocation ▫ New Operator ▫ Delete Operator ▫ Heap ▫ dot . and -> operators • Introduction to Linked List ▫ Types ▫ Advantages ▫ Disadvantages ▫ Applications ▫ Difference between Array and Linked List
  • 3. Objectives Overview • Insertion in Linked List with following criteria ▫ Start of the list ▫ End of the list ▫ Middle of the list ▫ Anywhere in the list • Deletion of a node from ▫ The Tail of the List ▫ The Head of the List ▫ A desired location in the list ▫ Delete node with a particular value
  • 5. Insertion A Node in the Linked List can be inserted at: 1. Beginning of the list. 2. End of the list. 3. Middle of the list 4. Anywhere in the list
  • 6. Insertion at the Beginning - Algorithm Steps to insert a Node at beginning : 1. Allocate a new node 2. Insert new element 3. Have new node point to old head 4. Update head to point to new node
  • 7.
  • 8. Implementation • int LinkedList :: addAtFront(node *n) { • int i = 0; • //making the next of the new Node point to Head • n->next = head; • //making the new Node as Head • head = n; • i++; • //returning the position where Node is added • return i; • }
  • 9. Insertion at the End - Algorithm Steps to insert a Node at End: 1. Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node point to new node 5. Update tail to point to new node
  • 10.
  • 11. Implementation • int LinkedList :: addAtEnd(node *n) { • if(head == NULL) { //If list is empty • head = n; //making the new Node as Head • n->next = NULL; //making the next pointe of the new Node as Null • } • else { • node *n2 = getLastNode(); //getting the last node • n2->next = n; } } • node* LinkedList :: getLastNode() { • node* ptr = head; //creating a pointer pointing to Head • //Iterating over the list till the node whose Next pointer points to null • //Return that node, because that will be the last node. • while(ptr->next!=NULL) { • //if Next is not Null, take the pointer one step forward • ptr = ptr->next; } • return ptr; }
  • 12. Insertion at the Middle - Algorithm Steps to insert a Node at Middle: 1. Allocate a new node 2. Insert new element 3. Go to node that should follow the one to add 4. Have that node point to the new node 5. Have new node point to node next node to the found node.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17. Insertion at a Specific Position - Algorithm Steps to insert a Node at Specified Position: 1. Traverse the Linked list up to position-1 nodes. 2. Once all the position-1 nodes are traversed, allocate memory and the given data to the new node. 3. Point the next pointer of the new node to the next of current node. 4. Point the next pointer of current node to the new node.
  • 18. Implementation • // function to insert a Node at required postion • void insertPos(Node** current, int pos, int data) • { • if (pos < 1 || pos > size + 1) • cout << "Invalid postion!" << endl; • else { • while (pos--) { • if (pos == 0) { • Node* temp = getNode(data); • temp->next = *current; • *current = temp; • } • else • current = &(*current)->next; • } • size++; • } • }
  • 20. Deletion A node in the linked list can be Deleted from: 1. The Tail of the List 2. The Head of the List 3. A Desired location in the list 4. Delete node with a particular value
  • 21. Deletion at the Beginning - Algorithm Steps: 1. Store Current Start in Another Temporary Pointer 2. Move Start Pointer One position Ahead 3. Delete temp i.e. Previous Starting Node as we have Updated Version of Start Pointer
  • 22.
  • 23.
  • 24.
  • 25. Implementation • Node *removeFirstNode (struct Node* head) • { • if (head == NULL) • return NULL; • • // Move the head pointer to the next node • Node *temp = head; • head = head->next; • • delete temp; • • return head; • }
  • 26. Deletion at the End - Algorithm Steps to Delete a Node at End : 1. Step 1: If FIRST = NULL then Write “Linked List is Empty” 2. Step 2: If FIRST->LINK = NULL then Return FIRST->INFO FIRST=NULL Else SAVE=FIRST Repeat while SAVE->LINK ≠ NULL PRED=SAVE SAVE=SAVE->LINK Return SAVE->INFO PRED->LINK=NULL 3. Step 3: Exit
  • 27.
  • 28. Implementation • Node* removeLastNode(struct Node* head) • { • if (head == NULL) • return NULL; • • if (head->next == NULL) • { • delete head; • return NULL; • } • • // Find the second last node • Node* second_last = head; • while (second_last->next->next != NULL) • second_last = second_last->next; • • // Delete last node • delete (second_last->next); • • // Change next of second last • second_last->next = NULL; • • return head; • }
  • 29. Deletion at a Desired Location - Algorithm Steps: 1. If start =NULL 2. Print”over flow” 3. Return 4. End if 5. Set ptr=start 6. Assign value=start -> info 7. Set start=start -> next(second node becomes the first node). 8. Release the node pointed by ptr to the memory heap. 9. Exit.
  • 30.
  • 31. Implementation • void deleteNode(struct Node **head_ref, int position) • { • if (*head_ref == NULL) // If linked list is empty • return; • struct Node* temp = *head_ref; // Store head node • • if (position == 0) // If head needs to be removed • { • *head_ref = temp->next; // Change head • free(temp); // free old head • return; • } • for (int i=0; temp!=NULL && i<position-1; i++) // Find previous node of the node to be deleted • temp = temp->next; • if (temp == NULL || temp->next == NULL) // If position is more than number of Nodes • return; • • // Node temp->next is the node to be deleted • // Store pointer to the next of node to be deleted • struct Node *next = temp->next->next; • • // Unlink the node from linked list • free(temp->next); // Free memory • • temp->next = next; // Unlink the deleted node from list • }
  • 32. Delete Node with a Particular Value - Algorithm Steps: 1. Store address of head in a double pointer till we find a non “key” node. This takes care of the 1st while loop to handle the special case of the head. 2. If a node is not “key” node then store the address of node->next in pp. 3. If we find a “key” node later on then change pp (ultimately node->next) to point to current node->next
  • 33.
  • 34. Implementation • void deleteKey(struct Node **head_ref, int key) • { • struct Node* temp = *head_ref, *prev; // Store head node • • • while (temp != NULL && temp->data == key) // If head node itself holds the key or multiple occurrences of key • { • *head_ref = temp->next; // Changed head • free(temp); // free old head • temp = *head_ref; // Change Temp • } • • while (temp != NULL) // Delete occurrences other than head • { • // Search for the key to be deleted, keep track of the • // previous node as we need to change 'prev->next' • while (temp != NULL && temp->data != key) • { • prev = temp; • temp = temp->next; • } • • if (temp == NULL) return; // If key was not present in linked list • • prev->next = temp->next; // Unlink the node from linked list • • free(temp); // Free memory • • temp = prev->next; //Update Temp for next iteration of outer loop • } • }
  • 35. Summary • Insertion in Linked List with following criteria ▫ Start of the list ▫ End of the list ▫ Middle of the list ▫ Anywhere in the list • Deletion of a node from ▫ The Tail of the List ▫ The Head of the List ▫ A desired location in the list ▫ Delete node with a particular value
  • 36. References • https://www.studytonight.com/data- structures/linear-linked-list • https://www.codelike.in/c/linked-list/ • http://www.c4learn.com/data-structure • https://www.slideshare.net/swajahatr/linked-list-c • http://www.thecodegallery.com/DSM/DeleteLast.ph p • https://www.slideshare.net/sathasivamr1/team-7- 42605180