Use C to print a single-chain table (without leading nodes) in reverse order.
In my previous blog posts, "insert linked list nodes in C Language", "delete linked list nodes in C Language", "Create a linked list by using the header plug-in and tail plug-in methods", and "basic operations on linked lists by using C language "to add, delete, modify, and query a single-chain table. Here we want to implement reverse printing of a single-chain table, using C. Upload the code to https://github.com/chenyufeng1991/reverselinkedlist.
The basic algorithm is:
(1) Use the tail plug method to build the original linked list;
(2) traverse the original linked list in sequence;
(3) retrieve the nodes in the traversal and use the header insertion method to create a new linked list;
(4) print the new linked list in reverse order;
The principle is that each inserted node in the header insertion method is the first node in the linked list. The first inserted node is the last node, and the last inserted node is the first node. So it will lead to reverse order.
The core code is as follows:
// Declare the reverse linked list Node * pReverseList; // the header insertion method creates the reverse linked list void HeadInsert (Node * pInsert) {if (pReverseList = NULL) {// This is the first node pReverseList = pInsert;} else {// The following is the header insert statement pInsert-> next = pReverseList; pReverseList = pInsert ;}} // use the header insertion method to create a new linked list void scanList (Node * pNode). {// first, judge whether the original linked list is empty. if (pNode = NULL) {printf ("% s FUNCTION execution, the original linked list is empty, and \ n" ,__ FUNCTION _ cannot be output in reverse order;} else {Node * pMove; // This Node is used to move the Node * pInsert in the original linked list. // This Node is the newly created insert Node. Point pInsert = (Node *) malloc (sizeof (Node); memset (pInsert, 0, sizeof (Node); pInsert-> next = NULL; pMove = pNode; while (pMove! = NULL) {// After traversing each node, call the header insertion function to insert the new linked list pInsert-> element = pMove-> element; HeadInsert (pInsert ); // allocate space for the next inserted Node pInsert = (Node *) malloc (sizeof (Node); memset (pInsert, 0, sizeof (Node )); pInsert-> next = NULL; pMove = pMove-> next;} printf ("% s FUNCTION execution, reverse linked list completed \ n" ,__ FUNCTION __);}}