-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReverseSublist.java
69 lines (57 loc) · 1.81 KB
/
ReverseSublist.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
58
59
60
61
62
63
64
65
66
67
68
69
package Leetcode;
/**
* @author kalpak
*
* Reverse a linked list from position m to n. Do it in one-pass.
*
* Note: 1 ≤ m ≤ n ≤ length of list.
*
* Example:
*
* Input: 1->2->3->4->5->NULL, m = 2, n = 4
* Output: 1->4->3->2->5->NULL
*
*/
public class ReverseSublist {
public static ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || head.next == null)
return head;
// dummy node to track the previous node
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode current = head;
ListNode prev = dummy;
// Set the current pointer to the place from where it needs to be reversed
for(int i = 1; i < m; i++) {
prev = current;
current = current.next;
}
// Reverse from position m to position n.
// We need to store the current and prev nodes to connect next after reversing
ListNode currentCopy = current;
ListNode prevCopy = prev;
ListNode next = null;
for(int i = m; i <= n; i++) {
next = currentCopy.next;
currentCopy.next = prevCopy;
prevCopy = currentCopy;
currentCopy = next;
}
// Connect the remaining part to the reversed linked list.
prev.next = prevCopy;
current.next = currentCopy;
return dummy.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(3);
l1.next.next.next = new ListNode(4);
l1.next.next.next.next = new ListNode(5);
ListNode result = reverseBetween(l1, 2, 5);
while(result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}