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;
}
本文介绍了一种在原地且只需一次遍历的情况下反转链表中指定区间的算法。以链表1->2->3->4->5->NULL为例,当m=2,n=4时,反转后的链表为1->4->3->2->5->NULL。文章提供了一个具体的Java实现方案。
862

被折叠的 条评论
为什么被折叠?



