0%

leetcode 92 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.demo.s92;

/**
* 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode.cn/problems/reverse-linked-list-ii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
//哑结点,方便返回结果
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
//记录翻转链表区间的前置节点
ListNode pre = dummyNode;
//指针移动到left-1位置,记为pre
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
// left位置节点
ListNode start = pre.next;
// cur节点
ListNode cur = pre.next;
//记录翻转链表区间的前置节点
ListNode p = null;
// 从left 到 right 范围链表翻转
for(int i = left; i <= right; i++) {
ListNode tmp = cur.next;
//当前节点指向前置节点
cur.next = p;
p = cur;
//翻转链表区间的前置节点 指向当前的节点,随着当前节点后移
pre.next=cur;
//遍历时移动到下一个节点
cur = tmp;
}
//当前节点不为空时,也就是没有遍历到最后一个节点
if(cur != null) {
//原先left位置节点指向下一个节点
start.next = cur;
}

return dummyNode.next;
}
}