Reverse code of linked list (c)
Address: http://blog.csdn.net/caroline_wendy
Reverse Sequence of linked listAs the basis for linked list operationsRequiredBe proficient in handwriting.
Mainly includeThree parts, A pointer records the subsequent nodes, a pointer records the previous node, pointing the current node to the previous node, moving to the next node, and moving the front and back pointers in turn.
Non-recursive reverse list AlgorithmCore codeOnly 10 rows.
Code:
/** Main. CPP ** created on: 2014.9.12 * Author: Spike * // * eclipse CDT, GCC 4.8.1 */# include <stdio. h> # include <stdlib. h> struct listnode {int data; listnode * Next;}; void printlist (listnode * head); listnode * reverselist (listnode * head); int main () {listnode * head = new listnode (); listnode * node1 = new listnode (); listnode * node2 = new listnode (); listnode * node3 = new listnode (); listnode * node4 = new lis Tnode (); head-> DATA = 0; head-> next = node1; node1-> DATA = 1; node1-> next = node2; node2-> DATA = 2; node2-> next = node3; node3-> DATA = 3; node3-> next = node4; node4-> DATA = 4; node4-> next = NULL; printlist (head ); listnode * Re = reverselist (head); printlist (re); Return 0;} listnode * reverselist (listnode * head) {If (Head = NULL | head-> next = NULL) {return head; /* If the linked list is empty or there is only one element, the system directly returns */} listnode * Prev = NULL; lis Tnode * Next = NULL; while (Head! = NULL) {next = head-> next; head-> next = Prev; Prev = head; head = next;} return Prev;} void printlist (listnode * head) {While (Head! = NULL) {printf ("% d", head-> data); Head = head-> next;} printf ("\ n ");}
Output:
0 1 2 3 4 4 3 2 1 0
Programming Algorithm-reverse code of linked list (c)