LeetCode92-反转链表II

LeetCode92-反转链表II

迭代法

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
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode pre = dummyHead;
//找到需要反转区间的前一个结点
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
//找到需要反转区间的最后一个结点
//从pre开始走
ListNode end = pre;
for (int i = 0; i < right - left + 1; i++) {
end = end.next;
}
//反转区间
ListNode r = pre.next;
ListNode curr = end.next;
//截断链表
pre.next = null;
end.next = null;
//反转区间内的链表
ListNode node = reverseList(r);
//重新接上
pre.next = node;
r.next = curr;
return dummyHead.next;
}

public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}