-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReverseLinkedListII.java
47 lines (40 loc) · 960 Bytes
/
ReverseLinkedListII.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
package LinkedList._92_Reverse_Linked_List_II;
import DataStructure.ListNode;
/**
* Created by hengwang on 2017-05-27.
*/
public class ReverseLinkedListII {
/**
* Use a dummyHead to track the new head after each reverse
* @param head
* @param m
* @param n
* @return
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return head;
}
ListNode current = head;
ListNode innerTail = head;
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
// Used to locate the new head of the list
head = dummyHead;
int i = 0;
while ( i < n) {
ListNode next = current.next;
if (i < m - 1) {
innerTail = next;
dummyHead = dummyHead.next;
} else {
current.next = dummyHead.next;
dummyHead.next = current;
}
i++;
current = next;
}
innerTail.next = current;
return head.next;
}
}