Tuesday, 15 January 2013

c - Traversing through a linked list -



c - Traversing through a linked list -

#include<stdio.h> struct node { int item; struct node *link }; main() { struct node *start,*list; int i; start = (struct node *)malloc(sizeof(struct node)); list = start; start->link = null; for(i=0;i<10;i++) { list->item = i; list->link = (struct node *)malloc(sizeof(struct node)); } list->link = null; while(start != null) { printf("%d\n",start->item); start = start->link; } }

as title suggests in trying traverse through linked list itteratively expected output 0 1 . . 9 , observed output : 9 wrong code ?

it because of 1 statement in code. forgot point next link, when tried allocate new link. because of allocating @ 1 pointer, having memory leak.

#include<stdio.h> struct node { int item; struct node *link }; main() { struct node *start,*list; int i; start = (struct node *)malloc(sizeof(struct node)); list = start; start->link = null; for(i=0;i<10;i++) { list->item = i; list->link = (struct node *)malloc(sizeof(struct node)); list = list->link; } list->link = null; while(start != null) { printf("%d\n",start->item); start = start->link; } }

c data-structures linked-list

No comments:

Post a Comment