#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* add_element( Node *head, int element ) {
Node *new_node;
new_node = malloc( sizeof( Node ) );
new_node->data = element;
new_node->next = head;
return new_node;
}
int length(Node *head) {
Node *current;
current = head;
int count = 0;
while( current != NULL ) {
count++;
current = current->next;
}
return count;
}
void print_list( Node *head ) {
Node *current;
current = head;
while( current != NULL ) {
if ( current == head ) {
printf( "{ %d", current->data );
}
else if ( current->next != NULL ) {
printf( ", %d", current->data );
}
else {
printf( ", %d }\n", current->data );
}
current = current->next;
}
}
int value_at(Node *head, int n){
Node *current;
int value;
current = head;
int count = 0;
while( current != NULL ) {
count++;
if(count==n){
value = current->data;
return value;
break;
}
current = current->next;
}
return -1;
}
Node* add_element_at_end(Node *head, int n){
Node *new_node;
new_node = malloc( sizeof( Node ) );
Node *end;
end = head;
while( end != NULL ) {
if(end->next==NULL) break;
end = end->next;
}
end->next = new_node;
new_node->data = n;
new_node->next = NULL;
}
int main() {
Node* list_head;
list_head = NULL;
list_head = add_element( list_head, 3 );
list_head = add_element( list_head, 2 );
list_head = add_element( list_head, 1 );
list_head = add_element( list_head, 0 );
add_element_at_end( list_head, 4 );
int len = length( list_head );
printf( "Length is: %d\n", len );
int p;
printf("Enter a position:");
scanf("%d",&p);
int value;
value=value_at(list_head, p);
printf("The value at node %d is: %d",p,value);
}