To delete a node from linked list can be performed in 3 positions:
- Delete from beginning
- Delete given node
- Delete from end
Delete from beginning:
- Store address of first node(head) in temporary node pointer.
- Move head to second node in linked list.
- Free memory of temporary node.
void del_begin(){
struct node *temp;
if(head==NULL){
printf("List is empty.\n");
}else{
temp=head;
head=head->next;
free(temp);
}
}
struct node *temp;
if(head==NULL){
printf("List is empty.\n");
}else{
temp=head;
head=head->next;
free(temp);
}
}
Delete given node:
void del_givennode(){
int nodeval;
struct node *ptr1,*ptr2;
if(head==NULL){
printf("List is empty.");
}else{
printf("Enter node value:\n");
scanf("%d",&nodeval);
ptr2=head;
while(ptr2->next!=NULL && ptr2->data!=nodeval){
ptr1=ptr2;
ptr2=ptr2->next;
}
if(ptr2->data==nodeval){
ptr1->next=ptr2->next;
free(ptr2);
}else{
printf("Node value not found in list.\n");
}
}
}
int nodeval;
struct node *ptr1,*ptr2;
if(head==NULL){
printf("List is empty.");
}else{
printf("Enter node value:\n");
scanf("%d",&nodeval);
ptr2=head;
while(ptr2->next!=NULL && ptr2->data!=nodeval){
ptr1=ptr2;
ptr2=ptr2->next;
}
if(ptr2->data==nodeval){
ptr1->next=ptr2->next;
free(ptr2);
}else{
printf("Node value not found in list.\n");
}
}
}
Delete from end:
- Move to two pointers, one(ptr2) points to last node of linked list another(ptr1) points to last but one node.
- Change address field of ptr1 with NULL to show it as last node.
- Free memory of ptr2
void del_end(){
struct node *ptr1,*ptr2;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr2=head;
while(ptr2->next!=NULL){
ptr1=ptr2;
ptr2=ptr2->next;
}
free(ptr2);
ptr1->next=NULL;
}
}
struct node *ptr1,*ptr2;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr2=head;
while(ptr2->next!=NULL){
ptr1=ptr2;
ptr2=ptr2->next;
}
free(ptr2);
ptr1->next=NULL;
}
}
Click on the below button for implementation of Singly Linked List with it's operations.
Related Programs
- Create Singly Linked List with N number of nodes and display.
- Perform insertion operation on Singly Linked List.
- Perform deletion operation on Singly Linked List.
- Reverse of Singly Linked List.
- Move last node of Singly Linked List to first.
- Swap first and last nodes in a Singly Linked List.
- Find the length of Singly Linked List.
- Find middle node of Singly Linked List