-
Notifications
You must be signed in to change notification settings - Fork 118
/
ReverseLinkedList2.java
57 lines (43 loc) · 1.35 KB
/
ReverseLinkedList2.java
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
package Algorithms;
public class ReverseLinkedList2 {
public static void main(String[] args) {
ReverseLinkedList2 rLL = new ReverseLinkedList2();
ListNode head = new ListNode(3);
head.next = new ListNode(5);
rLL.reverseBetween(head, 2, 2);
}
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode dumyNode = new ListNode(0);
dumyNode.next = head;
ListNode tmpHead = dumyNode;
// get the head before the reverse list;
for (int i = m; i > 1; i--) {
tmpHead = tmpHead.next;
}
// store the pre pointer
ListNode pre = null;
ListNode pst = tmpHead.next;
// store the head for later use.
ListNode reverseHead = pst;
// reverse the specific linkedlist.
for (int i = 0; i < n - m + 1; i++) {
ListNode tmp = pst.next;
pst.next = pre;
pre = pst;
pst = tmp;
}
tmpHead.next = pre;
reverseHead.next = pst;
if (m > 1) {
return head;
} else {
return pre;
}
}
}