-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0036_翻转链表II.java
More file actions
77 lines (73 loc) · 1.78 KB
/
Copy path0036_翻转链表II.java
File metadata and controls
77 lines (73 loc) · 1.78 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/*
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
// write your code here
if(m == n){
return head;
}
ListNode preM = null;
ListNode nextN = null;
ListNode nowM = null;
ListNode nowN = null;
int count = 1;
ListNode anoHead = head;
while(anoHead != null){
if(count == m-1){
preM = anoHead;
}
if(count == m){
nowM = anoHead;
}
if(count == n+1){
nextN = anoHead;
}
if(count == n){
nowN = anoHead;
}
count++;
anoHead = anoHead.next;
}
if(preM != null){
preM.next = Work(nowM,nowN);
if(nextN != null){
nowM.next = nextN;
}
return head;
}else{
head = Work(nowM,nowN);
if(nextN != null){
nowM.next = nextN;
}
return head;
}
}
public ListNode Work(ListNode head,ListNode tail){
ListNode pre = null;
ListNode now = head;
ListNode next = head;
while(now != tail){
next = now.next;
now.next = pre;
pre = now;
now = next;
}
now.next = pre;
return now;
}
}