-
Notifications
You must be signed in to change notification settings - Fork 0
/
10_2_Reverse Linked List II
50 lines (41 loc) · 1.04 KB
/
10_2_Reverse Linked List II
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
/**
* 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
ListNode myHead = new ListNode(0);
myHead.next = head;
ListNode tem = myHead;
ListNode temP = myHead;
int len = n-m+1;
while(m-->0) {
temP = tem;
tem = tem.next;
}
temP.next = reverse(tem , len);
return myHead.next;
}
public ListNode reverse(ListNode begin , int len){
if(len <=1) return begin;
ListNode p = begin , q = begin.next , n = q.next;
while(len-- > 1 && q!=null){
q.next = p ;
p = q;
q = n;
if(n!=null)
n = n.next;
}
begin.next = q;
return p;
}
}