Spread the love
Delete node in linked list without head pointer and traversing
Problem – You have given only pointer to a particular node to delete that node without using head node and traversing
Solution – There is no practical solution possible to delete node directly by given pointer, but there is a way to delete that node logically rather than physically in memory. And the solution is to copy the data from the next node to the current node by given pointer to be deleted and delete the next node. Something like following example
Note: This solution doesn’t work if the node to be deleted is the last node of the list.
#include<iostream> #include<stdlib.h> using namespace std; /* List Structure */ typedef struct Node { int data; struct Node *link; }node; node *head = NULL; // Head node to keep track of linked list /* Driver functions */ void DeleteNode(node *node_ptr); void insert(int data, int position); void print(); /* Main method */ int main() { insert(0,1); // Insert Element at first position LINKED-LIST = / 0 / insert(1,2); // Insert Element at second position LINKED-LIST = / 0 1 / insert(2,3); // Insert Element at third position LINKED-LIST = / 0 1 2 / insert(3,4); // Insert Element at fourth position LINKED-LIST = / 0 1 2 3/ insert(4,5); // Insert Element at fourth position LINKED-LIST = / 0 1 2 3 4/ print(); // Printing Elements of Linked List DeleteNode(head); //Deleting first node print(); // Printing Elements of Linked List return 0; } /* Delete node by given pointer */ void DeleteNode(node *node_ptr) { node *next = node_ptr->link; node_ptr->data = next->data; node_ptr->link = next->link; free(next); } /* Function for Inserting nodes at defined position */ void insert(int data, int position) { /* Declaring node */ node *temp = (node*)malloc(sizeof(node)); temp->data = data; temp->link = NULL; /* if node insertion at first point */ if(position==1) { temp->link = head; head = temp; return ; } /* Adding & Adjusting node links*/ node *traverse = head; for(int i=0; i<position-2; i++) { traverse = traverse->link; } temp->link = traverse->link; traverse->link = temp; } /* Function for Printing Linked List */ void print() { printf("\n Linked List = "); node *p = head; while(p) { printf(" %d",p->data); p = p->link; } printf(" \n\n"); }
Output
Suggested Reading
- Write a program to reverse a linked list using stack in c++
- Write a c program to implement a queue using array and linked list
- Write a c program to implement a stack using an array and linked list