forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedListII.java
More file actions
84 lines (83 loc) · 2.29 KB
/
ReverseLinkedListII.java
File metadata and controls
84 lines (83 loc) · 2.29 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
78
79
80
81
82
83
84
/**
* 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 sen = new ListNode(0);
sen.next = head;
ListNode prepre = sen, pre = head, cur = head.next, next = null;
int index = 1;
while(true){
if(index < m){
prepre = pre;
pre = cur;
cur = cur.next;
}
else if(index >= m && index < n){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
else if(index == n){
prepre.next.next = cur;
prepre.next = pre;
break;
}
++index;
}
return sen.next;
}
}
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
// Start typing your Java solution below
// DO NOT write main() function
//my solution
if(m == n)
return head;
ListNode cur = head, pre = null, start = null, end = null, next = null;
int count = 0;
while(count < n){
++count;
if(count == m - 1){
start = cur;
cur = cur.next;
}
else if(count == m){
end = cur;
pre = cur;
cur = cur.next;
}
else if(count >= m && count < n){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
else if(count == n){
next = cur.next;
if(start != null)
start.next = cur;
else
head = cur;
cur.next = pre;
end.next = next;
}
else{
cur = cur.next;
}
}
return head;
}
}