Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete nth node from both beginning and end of singly linked list

I’m just starting to learn linkedlist.

I can come up with an approach to delete a nth node from the beginning and end separately but I couldn’t take care of the checks needed to perform both at the same time.

Delete nth node from both beginning and end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INPUT:

1->2->3->4->5->6->7->8->9->10->NULL
N =4

OUTPUT:

1->2->3->5->6->8->9->10->NULL

C++ program or a general algorithm would be much appreciated.

>Solution :

Suppose you are at node 3.

helper = this -> next -> next;
delete this -> next;
this -> next = helper;

So basically you need to get to the node after the one you seek to delete prior to that deletion as then there will be no way of accessing it.

To check if there are any nodes at all:

if(root == NULL)
{
 /// there are no nodes
}

If there are nodes:

traverse = root;
int count = 0;
while(traverse != NULL)
{
   ++count;
   if(count == n)
   { /* you are at the nth node */ }
   traverse = traverse -> next;
}

Notice that if you delete node n and you are still at node (n-1), you will just have to do a seperate "shift of indicies," so to say, to remove another node. So if you want to delete another node that was previously the pth one, then just do in the if statement


///the deletion
++count;

Effectively you will get count == p when you arrive at the node that was the pth one until any deletions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading