Saturday, April 19, 2014

Remove Nth Node From End of List in a Singly linked list in C++



Remove Nth Node From End of List  in a Single linked list in C++
For example,
   Given linked list: 1->2->3->4->5, and N = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.
   Algorithm:
   Use two pointers *fast and *cur
   1)  Move pointer *fast  N step
   2)  Move pointer *fast and *cur the same step until *fast reaches end
   3) Now *cur point to next will be in the nth node counted from end of list
   4) Use  cur->next=cur->next->next;  to remove nth node from end of list
The code
struct Node *removeNthFromEnd(struct Node *head, int n) 
{
     Node *fast=head;
     Node *cur=head;
     for(int i=0;i<n;i++) fast=fast->next;
    if(fast==NULL) return head->next; //head node need to be removed
    while(fast->next!=NULL){
        fast=fast->next;
        cur=cur->next;
    }
    cur->next=cur->next->next;
    return head;
 }

Complete example code
#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* next;
};
// only for the 1st Node
void initNode(struct Node *head,int n){
    head->data = n;
    head->next =NULL;
}
// apending
void addNode(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;
    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }
        cur = cur->next;
    }
}
struct Node *removeNthFromEnd(struct Node *head, int n) 
{
     Node *fast=head;
     Node *cur=head;
     for(int i=0;i<n;i++) fast=fast->next;
    if(fast==NULL) return head->next; //head node need to be removed
    while(fast->next!=NULL){
        fast=fast->next;
        cur=cur->next;
    }
    cur->next=cur->next->next;
    return head;
 }
 void display(struct Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
}
int main()
{
    struct Node *head = new Node;
    initNode(head,1);
    addNode(head,2);
    addNode(head,3);
    addNode(head,4);
    addNode(head,5);
    display(head);
    cout<<"Remove  the second element from end"<<endl;
    removeNthFromEnd(head, 2);
    display(head);
}

Output
1 2 3 4 5
Remove  the second element from end
1 2 3 5
Video: Remove Nth Node From End of List  in a Single linked list in C++


No comments:

Post a Comment