Lecture 12-Operation On Singly Linked Lists
Lecture 12-Operation On Singly Linked Lists
SinglyLinked Lists
Data Structures & Algorithms
Lecture by Ms. Hira Kanwal
Department of CS/IT
List Overview
• Main Linked Lists Operations – Insert: inserts an element into the list
• Delete: removes and returns the specified position element from the
list
Linked List Traversal
• The idea here is to visit through the list from beginning to end. The
algorithm for traversing a list
• Start with the head of the list. Access the content of the head node .
• Then go to the next node(if exists) and access the node information
• Continue until no more nodes (that is, you have reached the null
node)
Implementation of Node
• struct node
• {
• int info;
• struct node *next;
• };
Info/Data Next
Node
Algorithm for traversal
• There can be three cases that will occur when we are inserting a
node in a linked list.
Note that we have to consider special cases such as list being empty.
In case of a list being empty, we will return the updated head of the
linked list because in this case, the inserted node is the first as well as
the last node of the linked list.
Insertion at end
• else
•{
• ptr=start;
• while(ptr->next !=NULL)
•{
• ptr=ptr->next ;
•}
• ptr->next =temp;
•}
Insertion after a given node
• We are given the reference to a node, and the new node is inserted
after the given node.
Insertion after a given node
• There can be three cases that will occur when we are deleting a node
in a linked list.
• int i,pos;
• struct node *temp,*ptr;
• printf("\n Enter the position of the node to be deleted: ");
• scanf("%d",&pos);
• if(pos==0)
• {
• ptr=start;
• start=start->next ;
• printf("\n The deleted element is:%d ",ptr->info );
• }
• else
• {
• ptr=start;
• for(i=0;i<pos;i++) { temp=ptr; ptr=ptr->next ;
• if(ptr==NULL)
•{
• printf("\n Position not Found:\n");
• return;
•}
•}
• temp->next =ptr->next ;
• printf("\n The deleted element is:%d ",ptr->info );
• free(ptr);
•}
•}
•}