-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathReverseLinkedListII.java
44 lines (38 loc) · 1.02 KB
/
ReverseLinkedListII.java
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
package com.dbc;
public class ReverseLinkedListII {
public 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 ListNode reverseBetween(ListNode head, int left, int right) {
ListNode preHead = new ListNode();
preHead.next = head;
ListNode res = preHead;
int count = 1;
while (count < left) {
preHead = preHead.next;
count++;
}
ListNode leftNode = preHead.next;
ListNode curNode = leftNode, nextNode = leftNode.next;
while (count < right) {
ListNode temp = nextNode.next;
nextNode.next = curNode;
curNode = nextNode;
nextNode = temp;
count++;
}
preHead.next = curNode;
leftNode.next = nextNode;
return res.next;
}
}