c - Printing the nodes of a linked list through a recursive function -
i've been asked make couple of programs using c. in 1 of these programs, need create linked list can stuff it. but, not allowed use global variables nor loops (while, for, etc.) in of these programs. here small program wrote fresh linked lists:
#include <stdio.h> #include <stdlib.h> struct node { int number; struct node *next; }; void create (struct node *, struct node *); void insert (struct node *, struct node *); void display (struct node *); int main(void) { struct node *head; struct node *current; struct node *temp; create ( head, current ); insert ( head, current ); temp = head; display ( temp ); } void create ( struct node *head, struct node *current ) { int a; printf("insert: "); scanf("%d", &a); current = malloc(sizeof(struct node)); current -> number = a; current -> next = null; head = current; } void insert ( struct node *head, struct node *current ) { int b; printf("insert: "); scanf("%d", &b); if ( b == -1 ) return; else { current = malloc(sizeof(struct node)); current -> number = b; current -> next = null; } insert ( head, current ); } void display ( struct node *temp ) { if ( temp != null ) { printf("%d \t", temp -> number); //error: exc_bad_access (code=exc_i386_gpflt) temp = temp -> next; display ( temp ); } else return; }
it's more or less standard code every book has, instead of loops use recursive functions. if closely, have problem display() function. error: exc_bad_access (code=exc_i386_gpflt) inside function, @ printf() line. can't print list on screen. i've been debugging 4 hours , can't find what's wrong, appreciated!
a third problem on top of 1 posted weather vane :
your insert weird. ask input , recursively call insert again. asking input, ... never hook in current in chain of linked list.
Comments
Post a Comment