ronith
7/6/2018 - 6:11 PM

Program for n’th node from the end of a Linked List

Counting from back starts indexing with 1.

// https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;

node* insert (node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
    return head;
}

int search (node* head, int n) {
    if (head!=NULL && n == 0)
        return head->data;
    node* list=head->next;
    n--;
    while (n>0 && list!=NULL) {
        list=list->next;
        n--;
    }
    if (list != NULL)
        return list->data;
    return -1;
}

int main () {
    int n,len=0;
    node* head=NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head,n);
    }
    node* temp = head;
    while (temp != NULL) {
        temp = temp->next;
        len++;
    }

    cout<< "Enter the index of the node from back: ";
    cin >> n;
    n=search(head, len-n);
    if (n==-1)
        cout<< "Index not found!";
    else
        cout<< "Element is "<<n;
}