I in the previous several blog "C Language Implementation linked list node insertion" "C Language Realization linked list node deletion" "C implementation of the head interpolation and tail interpolation method to build the chain list" C language to achieve the basic operation of the chain list to achieve the list of a lot of additions and deletions to check the operation. Here we want to implement the list in reverse order printing, using C to achieve. The code is uploaded to Https://github.com/chenyufeng1991/ReverseLinkedList.
The basic algorithm is:
(1) using the tail interpolation method to construct the original linked list;
(2) traverse the original linked list sequentially;
(3) Remove the nodes in the traversal using the head interpolation method to establish a new linked list;
(4) The new linked list after printing in reverse order;
The principle is that the head interpolation method each time the node inserted is the first of the list, the first inserted will become the last, the last inserted into the first node. So it will cause reverse order.
The core code is as follows:
The linked list after the declaration of the Reverse order node *preverselist;//header interpolation method to establish the reverse list of the linked list void Headinsert (node *pinsert) {if (preverselist = = NULL) {//This is the first node Preverselist = Pinsert; }else{//The following is a header-inserted statement pinsert->next = Preverselist; Preverselist = Pinsert; }}//iterates through the list and constructs a new linked list using the head interpolation method void Scanlist (Node *pnode) {////First determine if the original linked list is empty, if (Pnode = = NULL) {printf ("%s" function, the original linked list is empty, cannot reverse the output Out \ n ", __function__); }else{Node *pmove; This node is used to move node *pinsert in the original linked list; The node is a new insert node Pinsert = (node *) malloc (sizeof (node)); memset (pinsert, 0, sizeof (Node)); Pinsert->next = NULL; Pmove = Pnode; while (pmove! = NULL) {//traversal to each node, call the header interpolation function to insert a new linked list pinsert->element = pmove->element; Headinsert (Pinsert); Allocates space for the next node inserted Pinsert = (node *) malloc (sizeof (node)); memset (pinsert, 0, sizeof (Node)); Pinsert->next = NULL; Pmove = pmove->next; } PrintF ("%s function execution, reverse list complete \ n", __function__); }}
C language to implement reverse printing of linked list