Find the nth Element in a linked list.


/*
Find the nth Element 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;
    while(ptr!=NULL)
    {
        cout<data<<" ";
        ptr=ptr->next;
    }
    cout<<endl;
}

void findElement(struct node *header, int intPos)
{
    node *ptr;
    int matchPos=0;
    ptr=header;
    while(ptr!=NULL)
    {
        matchPos=matchPos+1;
        if(matchPos == intPos)
        {
            cout<<"The value at the node at position "<< intPos << " is: "<data;
        }
        ptr=ptr->next    ;
    }
}

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

    header=createlist();
    display(header);

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

Advertisements

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s