Question
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Code
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode p = head;
ListNode result = new ListNode(0);
result.next = p;
ListNode pre = result;
int len = 0;
Stack<ListNode> stacks = new Stack<>();
while (p != null) {
len++;
if (len < m) {
pre = p;
} else if (len >= m && len <= n) {
stacks.push(p);
} else if (len > n) {
break;
}
p = p.next;
}
while (!stacks.isEmpty()) {
ListNode node = stacks.pop();
pre.next = node;
pre = pre.next;
}
pre.next = p;
return result.next;
}