Showing posts with label questions on linked list. Show all posts
Showing posts with label questions on linked list. Show all posts

Saturday, 27 December 2014

Getting Kth element from last of Linked-List

// to find the kth element from the last of the linked list
#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
    int data;
    node *link;
}*head=NULL,*ptr;
int n=0;
int create()
{
   
    int value;
    cout<<"enter the data you want to enter in the linked list"<<endl;
    cin>>value;
    ptr=head;
    if(head==NULL)
    {
        ptr=new node;
        ptr->data=value;
        ptr->link=NULL;
        head=ptr;
        n++;
    }
    else
    {
        ptr=new node;
        ptr->data=value;
        ptr->link=head;
        head=ptr;
        n++;
    }
    return n;
}

void display()
{
    ptr=head;
    while(ptr!=NULL)
    {
        cout<<ptr->data<<"\t";
        ptr=ptr->link;
    }
    cout<<endl;
}

void find()
{
    int k;
    cout<<"enter the value of k"<<endl;
    cout<<"i.e enter the position of the element from the last"<<endl;
    cin>>k;
    int c=(n-k)+1;
    int c1=1;
    ptr=head;
    while(c1!=c)
    {
        c1++;
        ptr=ptr->link;
    }
    cout<<endl;
    cout<<"the kth element from the end is"<<endl;
    cout<<ptr->data<<endl;
    cout<<endl;
}

int main()
{
    int option;
    while(option!=4)
    {
    cout<<"enter 1. to insert"<<endl;
    cout<<"enter 2. to display"<<endl;
    cout<<"enter 3. to find"<<endl;
    cout<<"enter 4. to exit"<<endl;
    cin>>option;
    switch(option)
    {
        case 1: create();
        break;
        case 2: display();
        break;
        case 3: find();
        break;
    }
    }
    getch();
    return 0;
}




OUTPUT:--