Original: Step by step Write algorithm (the list reversal)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
List reversal is a frequently encountered topic in the interview environment, and is also a development requirement that we may encounter in actual development. Unlike linear reversals, the nodes of a one-way list need to be processed one at a. To show the difference between the two, we reverse the linear memory and the linked list, respectively:
(1) inversion analysis of common continuous memory data
STATUS normal_revert (int array[], int length) {int* pData; int index = length-1;if (NULL = = Array | | 0 = = length) return FA Lse;pdata = (int*) malloc (sizeof (int) * length), assert (NULL! = pData), memset (pData, 0, sizeof (int) * length), while (Index & gt;= 0) pdata[length-1-index] = Array[index], index--;memmove (array, pData, length * sizeof (int)); free (pData); return T RUE;}
We see that the continuous memory inversion function mainly does the following work:
1) Allocate memory as large as the original data
2) Start copying from the end of the original data
3) Use the data obtained by pdata to copy overwrite the original data and release the memory
(2) Reversal of linked list data
STATUS Link_revert (node** pnode) {node* pprevnode; node* pnextnode;if (NULL = = Pnode | | NULL = = *pnode) return False;pnextnode = (*pnode)->next; (*pnode)->next = Null;while (pnextnode) {Pprevnode = Pnextnode;pnextnode = Pnextnode->next;pprevnode->next = *pnode;*pnode = Pprevnode;} return TRUE;}
Unlike continuous memory, the reverse of a linked list node requires some of the following actions:
1) Determine if the pointer is empty, and whether the pointer pointer is empty
2) Divide the pointer into two parts, one is the linked list that has been successfully reversed, that is pnode, and the other is the linked list to be reversed, that is Pprevnode
3) iterate over the 2) until all nodes have accepted the reversal
It is recommended that you take a good look at the difference between the two.
Step-by-Step write algorithm (list reversal)