leetcode [#92] | GCidea's blog
目录

题目
Reverse a linked list from position m to n. Do it in-place and in one-pass.
Example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.Example:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
解决方案
1 | /** |
注意事项
- 使用“头指针”,从而去除头结点的特殊性。
- 难度在于要只一遍遍历且原地完成。
- 记录要翻转节点的前一个节点、要翻转的第一个节点、要翻转的最后一个节点。
- 核心代码:
1
2
3
4
5
6
7
8
9if(m <= tempA && tempA <= n){
ListNode next = p.next;
p.next = pre;
pre = p;
if(tempA == n){
end = p;
}
p = next;
}
是使用了链表翻转的典型做法。