The original title:
Paste the code first:
public class Solution92 {
public ListNode reverseBetween(ListNode head, int left, int right) {
//创建一个虚拟头节点以处理需要反转的节点是头节点的情况
ListNode newhead = new ListNode(-1);
newhead.next = head;
//创建cur节点使其指向left节点的前一个节点
ListNode cur = newhead;
for (int i = 0; i < left-1; i++) {
cur = cur.next;
}
//创建ret节点指向cur节点的next节点,即left节点
ListNode ret = cur.next;
//开始遍历链表,将left节点的后继节点移到cur节点之后
for (int i = 0; i < right-left; i++) {
ListNode retNext = ret.next;
ListNode curNext = cur.next;
cur.next = retNext;
ret.next = retNext.next;
retNext.next = curNext;
}
//返回虚拟头节点的后继节点
return newhead.next;
}
}
Thought analysis :
The title tells us that the linked list between the position left and the position right in the linked list is required to be reversed; for example, if left is set to 2 and right is set to 4, then the meaning is shown in the following figure:
First of all, when we encounter this problem, the first reversal method that comes to our mind should be to point the predecessor node whose position is the left node (hereinafter referred to as the left node) to the right node (hereinafter referred to as the right node), and then point the left node to the position of the right node (hereinafter referred to as the right node). The successor node of the right node, and then change the point of each node in this linked list to the previous node. However, this method is too complicated and redundant. It needs to find the left node and the right node, and then traverse it to change the point of each node in the linked list.
We must have encountered the phenomenon of queue jumping in our daily life: everyone wants to jump in the front, so one person jumps in the line once, and one person jumps in the line once, and the person at the front is slowly pushed to the back, The solution to this problem is similar;
Insert each node after the left position into the front of the team until the left node becomes the last node (the last node here refers to the last node of the linked list that needs to be reversed, not the last node of the entire linked list. One; the same is true for the front of the team, which refers to the front of the linked list that needs to be reversed), so that we only need to traverse the linked list once to complete the operation of reversing the linked list. The specific operation is as follows:
Here, in order to deal with the situation that the head node also needs to be reversed, a virtual head node is introduced to facilitate problem solving:
Then create the cur node to point to the predecessor of the left node:
Then start traversing the linked list:
Finally, return the next node of the newly created virtual head node: