forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedListII.java
More file actions
51 lines (43 loc) · 883 Bytes
/
ReverseLinkedListII.java
File metadata and controls
51 lines (43 loc) · 883 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
50
51
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(m==n) return head;
ListNode first = new ListNode(-1);
first.next = head;
ListNode p = head;
ListNode q, r;
head = first;
for(int i=1; i<m; i++){
first = first.next;
p = p.next;
}
if(p.next == null)
return head.next;
q = p.next;
r = q.next;
int count = 1;
while(count<n-m){
q.next = p;
p = q;
q = r;
r = q.next;
count++;
}
q.next = p;
first.next.next = r;
first.next = q;
return head.next;
}
}