-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathReverseLinkedListII.java
More file actions
49 lines (47 loc) · 980 Bytes
/
ReverseLinkedListII.java
File metadata and controls
49 lines (47 loc) · 980 Bytes
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
/**
* Reverse a linked list from position m to n. Do it in-place and in one-pass.
*
* For example:
*
* Given 1->2->3->4->5->NULL, m = 2 and n = 4,
*
* return 1->4->3->2->5->NULL.
*/
public class ReverseLinkedListII {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode start = new ListNode(0);
start.next = head;
ListNode low = start;
ListNode high = start;
ListNode p1 = null;
ListNode p2 = null;
for (int i = 0; i < m - 1; i++) {
low = low.next;
}
p1 = low;
low = low.next;
for (int i = 0; i < n; i++) {
high = high.next;
}
p2 = high.next;
high.next = null;
p1.next = reverseList(low);
while (p1.next != null) {
p1 = p1.next;
}
p1.next = p2;
return start.next;
}
private ListNode reverseList(ListNode low) {
ListNode cur = low;
ListNode prev = null;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}