# Delete a node when only a pointer/reference to a node is given in a singly linked list

0
295

## Given a pointer to a node in a singly linked list. We need to delete the node. Head of the node is not provided

### Example

Delete 5

Here only pointer of 5 given.

## Algorithm

Time complexity : O(1)

Step 1 : create a function which takes a node pointer and deletes it.
Step 2 : copy the data from the next node to the node to be deleted.
a)Â Â Â  Copy the data into present node.
b)Â Â Â  And change next of present node.
c)Â Â Â  Delete the next node of present node.

## C++ Program

``````#include <bits/stdc++.h>
using namespace std;

struct LL{
int data;
LL *next;
};

{
struct LL* curr=new LL;

curr->data=dataToBeInserted;
curr->next=NULL;

*head=curr; //if this is first node make this as head of list

else
{
curr->next=*head; //else make the current (new) node's next point to head and make this new node a the head
}

//O(1) constant time
}

void deleteNode(struct LL *&ptr) //take the reference so that whatever changes you do the ptr here it gets reflected everywhere
{
//According to question we do not know the head pointer
//Approach is first check if it is last node then simply make it NULL (dont delete orelse the previous node will point to dangling pointer).
//Else copy data of next node of the given node and delete the next node

if(ptr->next == NULL)
ptr = NULL;

else
{
struct LL * temp = ptr->next; //store the pointer to the next of given node
ptr->data = ptr->next->data;  //copy the contents of the next node
ptr->next = temp->next;  //make the next of given node to the remaining list
delete(temp);
}

}

{
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<" ->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}

int main()
{

struct LL *head = NULL; //initial list has no elements
cout<<"Current List is :-\n";

//Remove 'next' to check for all locations
cout<<"After deleting the node"<<endl;

return 0;
}``````

Normal
0

false
false
false

EN-IN
X-NONE
X-NONE

/* Style Definitions */
table.MsoNormalTable
{mso-style-name:”Table Normal”;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:””;
mso-para-margin-top:0cm;
mso-para-margin-right:0cm;
mso-para-margin-bottom:8.0pt;
mso-para-margin-left:0cm;
line-height:107%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:”Calibri”,”sans-serif”;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:”Times New Roman”;
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;}

Previous articleCheck if two linked lists are identical
If you have come this far, it means that you liked what you are reading. I am a software developer (graduated from BITS Pilani). I love writing technical articles on programming and data structures.