Remove node in a singly linked list.

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

EXAMPLE

Input: the node c from the linked list a->b->c->d->e

Result: nothing is returned, but the new linked list looks like a->b->d->e

C++:
01 void rmNode(Node** head, Node* toRemove)
02 {
03     if(*head==toRemove){
04         Node* tmp=*head;
05         *head=(*head)->next;
06         delete tmp;
07         return;
08     }
09     Node* prv=*head;
10     Node* tmp=(*head)->next;
11     while(tmp){
12         if(tmp==toRemove){
13             prv->next=tmp->next;
14             delete tmp;
15             return;
16         }
17         prv=tmp;
18         tmp=tmp->next;
19     }
20 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s