Wednesday 15 August 2012

data structures - C code: cannot print out the whole linked list as I expected -



data structures - C code: cannot print out the whole linked list as I expected -

i've been staring @ code long , still doesn't work expected to. code should enable user initialize linked list entering length of , info of every node, , prints out info afterwards.

#include "stdio.h" #include "stdlib.h" typedef struct node { int data; struct node* next; } node; int n,x,i; node* head = (node*)malloc(sizeof(node)); void init(int x, node* temp){ node* newnode = (node*)malloc(sizeof(node)); temp->data = x; temp->next = newnode; temp = newnode; } void print(){ node* temp = head; while(temp != null){ printf("%d ", temp->data); temp = temp->next; } } int main(){ printf("please come in number of nodes in linked list:\n"); scanf("%d", &n); node* temp = head; printf("please come in info of node:\n"); for(i=0;i<n;i++){ scanf("%d", &x); init(x,temp); } print(); }

i think maybe there's problem head node. run code, info seems inserted without problem cannot print out origin print() function.

this looks when run it.

please come in number of nodes in linked list: 4 please come in info of node: 1 2 3 4 4 -842150451 press key go on

i guess may have missed basic here, sorry if have since i'm new learning c , info structure.

this function

void init(int x, node* temp){ node* newnode = (node*)malloc(sizeof(node)); temp->data = x; temp->next = newnode; temp = newnode; }

doesn't alter node in calling function. not that, newnode memory leak.

your code needs bit of re-working. init() can designed add together items @ end of list or @ start of list. have decide behavior want implement. after that, init needs reworked bit match expected behavior.

c data-structures

No comments:

Post a Comment