[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
Chain table reversal is a frequently encountered problem in the interview environment and also a development requirement we may encounter in actual development. Unlike linear reversal, nodes in a one-way linked list must be processed one by one. To show the differences between the two, we reverse the linear memory and the linked list respectively:
(1) Reverse Analysis of normal continuous memory data
STATUS normal_revert (int array [], int length)
{
Int * pData;
Int index = length-1;
If (NULL = array | 0 = length)
Return FALSE;
PData = (int *) malloc (sizeof (int) * length );
Assert (NULL! = PData );
Memset (pData, 0, sizeof (int) * length );
While (index> = 0)
PData [length-1-index] = array [index], index --;
Memmove (array, pData, length * sizeof (int ));
Free (pData );
Return TRUE;
}
STATUS normal_revert (int array [], int length)
{
Int * pData;
Int index = length-1;
If (NULL = array | 0 = length)
Return FALSE;
PData = (int *) malloc (sizeof (int) * length );
Assert (NULL! = PData );
Memset (pData, 0, sizeof (int) * length );
While (index> = 0)
PData [length-1-index] = array [index], index --;
Memmove (array, pData, length * sizeof (int ));
Free (pData );
Return TRUE;
}
We can see that the continuous memory reversal function mainly performs the following work:
1) allocate memory as large as the original data
2) copy from the end of the original data
3) use the data obtained by pData to copy and overwrite the original data and release the memory.
(2) reverse 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;
}
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 the continuous memory, you need to perform the following operations to reverse the linked list node:
1) judge whether the pointer is null and whether the pointer is null
2) divide the pointer into two parts: one is the linked list that has been successfully reversed, that is, pNode; the other is the linked list to be reversed, that is, pPrevNode
3) perform loop iteration on 2) until all nodes have been reversed
We suggest you take a good look at the differences between the two.