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.
這題看了答案,在紙上寫了一遍思路還蠻清晰的欧宜。我發(fā)現(xiàn)Leetcode自己的solutions里面的高票答案就挺好的(https://discuss.leetcode.com/topic/8976/simple-java-solution-with-clear-explanation)蜀备。
思想:
這題思想是一直讓start繞過它后面的節(jié)點(diǎn)then,接到then.next上去,然后then接到逆序list的首位鉴扫,也就是pre.next烦秩。
注意的地方:
for循環(huán)中的第二句then.next應(yīng)該指向pre.next,而不是start刻获。
因?yàn)閟tart和then一直在向右平移蜀涨,交換過一次后pre已經(jīng)不會(huì)指向start。
draft
public ListNode reverseBetween(ListNode head, int m, int n) {
// we need for nodes
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode start;
ListNode then;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
start = pre.next;
then = start.next;
for (int i = 0; i < n - m; i++) {//交換n-m次
start.next = then.next;
then.next = pre.next; //it has to be pre.next,而不是start厚柳,因?yàn)閟tart和then一直在向右平移氧枣,交換過一次后pre已經(jīng)不會(huì)指向start
pre.next = then;
then = start.next;
}
return dummy.next;
}
今天是周五。買了一臺(tái)iPhone别垮。