forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse Linked List II.java
More file actions
48 lines (45 loc) · 932 Bytes
/
Reverse Linked List II.java
File metadata and controls
48 lines (45 loc) · 932 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
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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) return head;
int start = 1, end = 0;
ListNode s = head;
ListNode p = null;
while (start++ < m && s != null) {
p = s;
s = s.next;
}
ListNode cur = null;
ListNode next = null;
ListNode prev = null;
end = m;
cur = s;
while (end++ <= n && cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
s.next = cur;
if (p != null) {
p.next = prev;
return head;
} else {
return prev;
}
}
}