The following procedures have a few points of attention, see notes.
1 # include <stdio. h> 2 # include <stdlib. h> 3 4/* This format is used to write struct later. that is, typedef annotation. the upper and lower listnodes must be the same. */5 typedef struct listnode 6 {7 int key; 8 struct listnode * Next; 9} listnode; 10 11 static listnode * create_list (); 12 static void print_list (listnode *); 13 static void reverse_print (listnode *); 14 15 int main (INT argc, char * argv []) 16 {17 listnode * head = NULL;
/* Create_list (head) cannot be used directly. Why?
** When a function is called, parameter passing is equivalent to a value assignment. null pointers cannot be assigned to other pointers. */18 head = create_list (); 19 print_list (head); 20 21 reverse_print (head); 22 printf ("\ n"); 23 return 0; 24} 25 26 static listnode * create_list () 27 {28 int C; 29 listnode * P; 30 31 head = (listnode *) malloc (sizeof (listnode )); 32 head-> next = NULL; 33 P = head; 34 35 scanf ("% d", & C); 36 while (C! =-1) 37 {38 P-> next = (listnode *) malloc (sizeof (listnode); 39 p-> next-> key = C; 40 p-> next = NULL; 41 P = p-> next; 42 scanf ("% d", & C); 43} 44 return head; 45} 46 47 48 static void print_list (listnode * head) 49 {50 listnode * P; 51 P = head-> next; 52 53 While (P! = NULL) 54 {55 printf ("% d", p-> key); 56 p = p-> next; 57} 58 printf ("\ n "); 59} 60/* this recursive call is recommended. */61 static void reverse_print (listnode * head) 62 {63 listnode * P; 64 65 p = head-> next; 66 If (P = NULL) 67 {68 return; 69} 70 else71 {72 reverse_print (p); 73} 74 75 printf ("% d", p-> key); 76}
Create a linked list and print it in reverse order