/*
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);
}