CareerCup-2.2

Implement an algorithm to find the nth to last element of a singly linked list

#include <iostream>  
using namespace std;  
  
// Creating a Linked List:  
struct Node  
{  
    Node(int d):data(d){next = NULL;};  
    int data;  
    Node* next;  
};  
  
Node* findNth(Node* head, int n)  
{  
    if(head == NULL || n < 0)  
        return NULL;  
    Node *p, *q;  
    p = q = head;  
    while(n--)  
    {  
        q = q->next;  
        if(q == NULL)  
            return NULL;  
    }  
    while(q->next != NULL)  
    {  
        p = p->next;  
        q = q->next;  
    }  
    return p;  
};  
  
int main()  
{  
    Node* head = new Node(1);  
    head->next = new Node(2);  
    head->next->next = new Node(3);  
    head->next->next->next = new Node(4);  
    head->next->next->next->next = new Node(5);  
    head->next->next->next->next->next = new Node(6);  
    findNth(head, -1);  
    findNth(head, 1);  
    system("pause");   
};

Comments

comments powered by Disqus