forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverselinkedinlist2.java
More file actions
executable file
·41 lines (39 loc) · 995 Bytes
/
reverselinkedinlist2.java
File metadata and controls
executable file
·41 lines (39 loc) · 995 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
/**
* 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(n-m<=0) return head;
ListNode prev = new ListNode(0);
prev.next = head;
ListNode p = prev;
// reverse from p.next
for(int i=0;i<m-1;i++){
p = p.next;
}
ListNode pnext = p.next;
ListNode qprev = p;
ListNode qnext = p.next.next;
ListNode q = p.next;
for(int i=0;i<n-m;i++){
q.next = qprev;
qprev = q;
q = qnext;
qnext = qnext.next;
}
q.next = qprev;
p.next = q;
pnext.next = qnext;
return prev.next;
}
}