Deletion From Singly Linked List What is Singly Linked List A singly linked list is a collection of nodes. Each node has two parts - the first part is the data and the second part the next pointer. The data part holds the actual data for the node. The next pointer points to the next node in the list. The nodes are connected with each other in single direction. There is a head pointer which always points to the first node in the linked list and the last node refers to null which signifies the end of the node. Data Next
Deleting a Node in Singly Linked List Here we have three cases:- Deleting the first node. Deleting the last node. Deleting the intermediate node. Deleting the first node Here we apply two steps:- Making the start pointer point towards the 2 nd node. Deleting the first node using delete keyword. void delete_from_first () { struct node* temp=head; head=head->next/temp->next; free(temp); }
data next data next data next data next data next data next data next data next data next data next data next data next temp_ptr = head head = head->next temp_ptr->next = null Deallocate the memory for node 1 temp_ptr = null temp _ptr head head null head null null null
Deleting the last node Here we apply two steps:- Making the second last node’s next pointer point to NULL. Deleting the last node via delete keyword . void delete_from_last () { struct node *temp=head, *temp2; while(temp->next) { temp2=temp; temp=temp->next; } temp2->next=NULL; free(temp); } null head temp
data next data next data next data next head temp_ptr null temp_ptr = head N = number of nodes in the linked list for ( counter = 1 ; counter < N - 1 ; counter++ ) { temp_ptr = temp_ptr->next } last_node = temp_ptr->next deallocate memory of the node pointed by last node temp_ptr->next = null last_node = null data next data next data next data next head temp_ptr data next data next data next data next head temp_ptr null Last_node data next data next data next data next head temp_ptr Last_node null null null
Deleting the third node Here we make the next pointer of the node previous to the node being deleted ,point to the successor node of the node to be deleted and then delete the node using. delete keyword. void delete_from_any_position (int pos) { int i ; struct node *temp=head, *temp2; for( i =2 ; i <pos ; i ++) { temp=temp->next; } temp2=temp->next temp->next=temp2->next; free(temp2); } head temp null
temp_ptr = head current = head for (counter = 1 ; counter < 2 ; counter++) { temp_ptr = temp_ptr->next } for (counter = 1 ; counter < 3 ; counter++) { current = current->next } temp_ptr ->next->next = null deallocate memory for temp_ptr ->next temp_ptr->next = current current = null temp_ptr = null data next data next data next data next temp_ptr null head current_ptr data next data next data next data next temp_ptr head data next data next data next data next temp_ptr head current_ptr null null current_ptr null