Topic describes
Given the head node of a single linked list, reverse the list and return the reversed list.
Given: 1 -> 2 -> 3 -> 4 -> 5
Return: 5 -> 4 -> 3 -> 2 -> 1
code
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; * /
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre = nullptr, *curr = head, *next = nullptr;
while(curr ! =nullptr) {
next = curr->next;
curr->next = pre;
// The pre and curr nodes are one step behind each other
pre = curr;
curr = next;
}
returnpre; }};Copy the code
Their thinking
The initial state
The initial state just needs to bepre
andnext
The node tonullptr
.curr
The node tohead
Node.
Cycle steps
The first step we need to do is savecurr
The next node of a node for subsequent usecurr
The node is moved one step back.
Reverse curr to the pre node.
- The tail node after the inversion should point to
nullptr
, sopre
The initial node isnullptr
. - Records are required before inversion
curr
Next node, so thatcurr
Next move back.
whencurr
After reversing the pointing direction, the firstpre
The node tocurr
The current position is equivalent topre
The node moves back one step.
At this point, point the curr node to the next node to complete the backward step.