Review linked list Inversion
# Include <stdio. h> # include <malloc. h> typedef int elemtype; typedef struct node {int data; struct node * Next;} node, * List; // use array arr to initialize data in the linked list; in this example, the chain table has no header point int initlist (list * List, elemtype * arr, int num) {int I = 0; node * tail_node; node * tmp_node; * List = (list) malloc (sizeof (node); If (null = * List) return; (* List)-> DATA = arr [I]; (* List) -> next = NULL; tail_node = * List; for (I = 1; I <num; I ++) {tmp_node = (node *) malloc (sizeof (node )); if (null = tmp_node) return; tmp_node-> DATA = arr [I]; tmp_node-> next = NULL; tail_node-> next = tmp_node; tail_node = tmp_node ;}} void traveselist (list) {node * tmp_node; If (null = List) return; tmp_node = List; while (tmp_node) {printf ("% d ", tmp_node-> data); tmp_node = tmp_node-> next;} printf ("\ n");} void reverselist (list * List) {node * p_pre = NULL; node * p_cur = NULL; node * p_nxt = NULL; If (null = List) return; p_cur = (* List)-> next; p_pre = * List; p_pre-> next = NULL; while (p_cur) {p_nxt = p_cur-> next; p_cur-> next = p_pre; p_pre = p_cur; p_cur = p_nxt ;} * List = p_pre;} // implement recursive inversion. The returned chain table header is the same as the non-recursive method described above, invert the pointer of the current node and the node (Save the current node and the next node of the node before reversing to complete the same operation of the subsequent nodes-done through recursion) node * reverse (node * p_cur, node * p_pre) {If (null = p_cur-> next) {p_cur-> next = p_pre; return p_cur ;} else {node * p_nxt = p_cur-> next; p_cur-> next = p_pre; reverse (p_nxt, p_cur) ;}} int main () {list head; node * TMP; int array [] = {3, 5, 7, 8, 2}; initlist (& head, array, 5); traveselist (head); printf ("reverse list: "); reverselist (& head); traveselist (head); printf (" reverse list: "); Head = reverse (Head, null); traveselist (head ); return 0 ;}
Chain table inversion (recursive and non-recursive implementations)