-
Notifications
You must be signed in to change notification settings - Fork 57
/
Solution.java
59 lines (58 loc) · 1.36 KB
/
Solution.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 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.
*
*Note:
*Given m, n satisfy the following condition:
*1 ≤ m ≤ n ≤ length of list.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n) {
return head;
}
ListNode start = null, end = null, curr = head;
ListNode prev = null, prevMark = null, tmp = null;
int idx = 1;
while (curr != null) {
if (idx == m - 1) {
prevMark = curr;
}
if (idx == m) {
start = curr;
}
if (idx == n) {
end = curr.next;
break;
}
curr = curr.next;
idx++;
}
curr = start;
prev = end;
while (curr != end) {
tmp = curr.next;
curr.next = prev;
prev = curr;
curr = tmp;
}
if (prevMark != null) {
prevMark.next = prev;
} else {
head = prev;
}
return head;
}
}