// Enter several integers on the keyboard, and create a singly linked list with head nodes in reverse order of input data (header insertion creates a singly linked list) #include <stdio.h> #include <stdlib.h> typedef struct Link { int data; struct Link * next; } link; // InitLink (link * head_node) { head_node = (link *) malloc (sizeof (link)); // Create head node head_node-> data = 0; // The initial assignment value of the head node data field is 0 head_node-> next = NULL; link * ptail = head_node; // The header insertion assignment printf ("Enter several values to save in reverse order to the linked list: \ n"); int num = 0; while (num! = -1) {// Enter -1 to end scanf ("% d", & num); link * new_node = (link *) malloc (sizeof (link)); // Apply for a new node new_node-> data = num; // Assign initial value to new node new_node-> next = head_node; // The pointer field of the new node is the last node head_node = new_node; // The new node becomes the last node (head node, head node is in the back) ptail = new_node; // tail The pointer points to this new node, keep moving forward } printf ("The value pointed by the tail pointer is:% d \ n", head_node-> next-> data); // return ptail; // will point to the last node The tail pointer returns return head_node; } // Traversing the linked list (established in reverse order, sequential traversal) void showLink (link * head_node) { link * tmp = head_node-> next; // The next node from the head node is the first one The node begins to traverse to avoid outputting the end flag -1 while (tmp! = NULL) { // if (tmp-> data == -1) { // break; // Sequential traversal, the end flag -1 is not output. Control, otherwise none will be output // printf ("% d", tmp-> data); tmp = tmp-> next; } } void main() { link * myHeadNode = NULL; myHeadNode = initLink (myHeadNode); // Get the initialized head node printf ("The linked list created in reverse order is: \ n"); showLink (myHeadNode); }
0 is the value in the head node, you can not print, traverse to tmp-> data == 0 when traversing, just exit the traversal.