Interview Question
Given a linked list, and a positive integer n, find the nth element of a linked list.
Solution
#include<stdio.h>
#include<stdlib.h>
struct node {
struct node * next ;
int data ;
} * head = NULL ;
void push ( int val )
{
struct node * newnode = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
newnode -> next = NULL ;
newnode -> data = val ;
struct node * ptr = head ;
if ( ptr == NULL )
head = newnode ;
else {
while ( ptr -> next )
ptr = ptr -> next ;
ptr -> next = newnode ;
}
}
void print ()
{
struct node * itr = head ;
while ( itr )
{
printf ( " %d " , itr -> data ) ;
itr = itr -> next ;
}
}
void find ( int idx )
{
struct node * ptr = head ;
printf ( " \n At position %d , " , idx ) ;
while( -- idx )
{
if ( !ptr )
break ;
ptr = ptr -> next ;
}
printf ( "Found %d ." , ptr -> data ) ;
}
int main ()
{
push ( 3 ) ;
push ( 4 ) ;
push ( 2 ) ;
push ( 1 ) ;
push ( 5 ) ;
print() ;
find ( 2 ) ;
return 0 ;
}