Find the nth Element from last in a linked list.


/*
Find the nth Element from last in a linked list.
*/

#include

using namespace std;

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

struct node* createlist()
{
    node *nodeHolder,*pointerToTheFirstNode, *temp;

    int elementCount=0;
    pointerToTheFirstNode = (node*)malloc(sizeof(node));
    temp=pointerToTheFirstNode;
    cout<<"Enter the number of elements you want in the list:    ";
    cin>>elementCount;
    cout<<endl;

    while(elementCount!=0)
    {
    temp->next=(node*)malloc(sizeof(node));
    cout<<"Enter the elements for the nodes:    ";
    cin>>temp->data;
    nodeHolder=temp;   
    temp=temp->next;
    elementCount–;
    }
    nodeHolder->next =NULL;
    free(temp);
    return pointerToTheFirstNode;
}

void display(struct node *headerPointer)
{

    node *ptr;
    ptr = headerPointer;
    cout<<endl<<"The list that we just created is:    ";
    while(ptr!=NULL)
    {
        cout<data<<" ";
        ptr=ptr->next;
    }
    cout<<endl;
}

int lenlist(struct node *header)
{
    node *ptr;
    int len=0;
    ptr=header;
    while(ptr!=NULL)
    {
        len=len+1;
        ptr=ptr->next;
    };
    return len;
}

void findElementFromLast(struct node *header, int intPos)
{
    node *ptr;
    ptr=header;
    int matchPos=0;
    int listLen = lenlist(ptr);
    cout<<"The length of the list is:    "<<listLen<<endl;
    cout<<"The element that is at "<< intPos <<" from the last node will be at "<<listLen-intPos<< " from the first node."<<endl;

    while(ptr!=NULL)
    {
        matchPos=matchPos+1;
        if(matchPos ==     (listLen-intPos))
        {
            cout<<"The value of the node that is at "<< intPos <<"th position from last is: "<data;
        }
        ptr=ptr->next    ;
    }
}

void main()
{
    node *header;
    int intPosFromLast=0;

    header=createlist();
    display(header);

    cout<<"Enter the position element that you want to find in the list we just created:    ";
    cin>>intPosFromLast;
    findElementFromLast(header,intPosFromLast);
}

Advertisement

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 )

Facebook photo

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

Connecting to %s