Building a linked list in C

The following program shows how a simple, linear linked list can be constructed in C, using dynamic memory allocation and pointers.
#include
#include

struct list_el {
int val;
struct list_el * next;
};

typedef struct list_el item;

void main() {
item * curr, * head;
int i;

head = NULL;

for(i=1;i<=10;i++) {
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next  = head;
head = curr;
}

curr = head;

while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
}

No comments:

Post a Comment