Thursday, August 1, 2013
2:35 PM

Simple and Best Linked List example in C

Hi,
Below linked list example is taken from http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html it is easy and working properly. I did small modifications to it

This example is single linked list


#include<stdlib.h>
#include<stdio.h>

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


void main() {
   struct list * head = NULL;
   struct list * curr = NULL;


//Storing data into Linked list
      curr = (struct list *)malloc(sizeof(struct list));
      curr->val = 10;
      curr->next  = head;
      head = curr;

//Storing data into Linked list
      curr = (struct list *)malloc(sizeof(struct list));
      curr->val = 5;
      curr->next  = head;
      head = curr;


   curr = head;

//Reading data from Linked list (it print from tail)
   while(curr) {
      printf("%d\n", curr->val);
      curr = curr->next ;
   }
}

Compilation Output


[root@system Desktop]# gcc linkedlist.c 
[root@system Desktop]# ./a.out
5
10
[root@system Desktop]# 



0 comments:

Post a Comment

:) :)) ;(( :-) =)) ;( ;-( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ $-) (b) (f) x-) (k) (h) (c) cheer
Click to see the code!
To insert emoticon you must added at least one space before the code.