C Program
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head,int x)
{
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=*head;
*head=temp;
}
void print(struct node *head)
{
printf("Linked list:");
while(head)
{
printf("-->%d",head->data);
head=head->next;
}
printf("\n");
}
int GetNth(struct node* head,int index)
{
int count=1;
while(head)
{
if(count==index)
return head->data;
count++;
head=head->next;
}
return -1;
}
int main()
{
int n,i,x,index;
struct node *head=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
push(&head,x);
}
scanf("%d",&index);
print(head);
printf("Node at index=%d:%d",index,GetNth(head,index));
return 0;
}
0 Comments