c - Different functions to print a linked list -
i saw 2 (different?) implementations of function print linked list. let me first give code example:
#include <stdio.h> #include <stdlib.h> struct node { int x; struct node *next; }; void free_list(struct node *current); void print_list_a(struct node *current); void print_list_b(struct node *head); int main() { struct node *head; struct node *second; struct node *third; head = null; second = null; third = null; head = malloc(sizeof(struct node)); if (!head) { exit(exit_failure); } second = malloc(sizeof(struct node)); if (!second) { exit(exit_failure); } third = malloc(sizeof(struct node)); if (!third) { exit(exit_failure); } head->x = 1; head->next = second; second->x = 2; second->next = third; third->x = 3; third->next = null; print_list_a(head); print_list_b(head); free_list(head); exit(exit_success); }
above have declared 2 print functions print_list_a()
, print_list_b()
. definitions this:
void print_list_a(struct node *current) { while (current != null) { printf("%d->", current->x); current = current->next; } } void print_list_b(struct node *head) { struct node *current; current = head; while (current != null) { printf("%d->", current->x); current = current->next; } {
my questions are: a) there real difference between print_list_a()
, print_list_b()
? , b) there advantage of 1 on other aka preferred? bit confused both achieve same. advantage print_list_b()
can see head
appears in functions parameter list.
there no difference between functions. both uses local variable store current node in list. take account function parameters local variables of function.
nevertheless me prefer following definition of function
void print_list_b( const struct node *head ) { ( const struct node *current = head; current != null; current = current->next ) { printf( "%d->", current->x ); } }
or following
void print_list_b( const struct node *current ) { ( ; current != null; current = current->next ) { printf( "%d->", current->x ); } }
but use loop.:)
take account compiler can generate same object code loops: while or for.:)
i suggest consider 1 more print_list functions.:)
void print_list( const struct node *current ) { if ( current != null ) { printf( "%d->", current->x ); print_list( current->next ); } } void print_list( const struct node *current ) { if ( current != null ) { print_list( current->next ); printf( "%d->", current->x ); } }
Comments
Post a Comment