We assume that the nodes of the one-way linked list are as follows:
Template <typename T>
Class list_node
{
Public:
List_node * next;
T data;
};
This is the most basic question of data structure. There are two ways to solve this question:
Method 1:
Void reverse (node * & head)
{
If (Head = 0) | (Head-> next = 0) return; // Boundary Detection
Node * pnext = 0;
Node * pprev = head; // Save the head node of the linked list
Node * pcur = head-> next; // get the current node
While (pcur! = 0)
{
Pnext = pcur-> next; // save the next node
Pcur-> next = pprev; // set the next node of the current node to the previous Node
Pprev = pcur; // Save the current node as the previous Node
Pcur = pnext; // set the current node to the next node
}
}
This is a general method. In short, several temporary variables are used to traverse the entire linked list and set the next node of the current node to the previous node.
Note:
It is best to draw a picture of the chain table reversal. It is really confusing for new users to simply look at the code.
The normal sequence of the linked list is that the next of the previous node points to the next node. Reversing refers to pointing the next node of the next node to the forward node,
Therefore, pcur-> next = pprev; completes this function. However, this only completes the reversal of the two nodes, so the corresponding
The next of the node is saved as pnext = pcur-> next; used as the next pcur = pnext of the current node; In the next reversal, the current node
It becomes the front node in the next reversal. Pprev = pcur;
Until the current node is null, that is, all transformations;
Method 2:
Node * reverse (node * pnode, node * & head)
{
If (pnode = 0) | (pnode-> next = 0) // recursive exit condition
{
Head = pnode; // cut the linked list; otherwise, a loop is formed.
Return pnode;
}
Node * temp = reserve (pnode-> next, head); // Recursion
Temp-> next = pnode; // set the next node to the current node, which is a front Node
Return pnode; // return the current node
}