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.
這題看了答案,在紙上寫了一遍思路還蠻清晰的。我發現Leetcode自己的solutions里面的高票答案就挺好的(https://discuss.leetcode.com/topic/8976/simple-java-solution-with-clear-explanation)。
思想:
這題思想是一直讓start繞過它后面的節點then,接到then.next上去,然后then接到逆序list的首位,也就是pre.next。
注意的地方:
for循環中的第二句then.next應該指向pre.next,而不是start。
因為start和then一直在向右平移,交換過一次后pre已經不會指向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,因為start和then一直在向右平移,交換過一次后pre已經不會指向start
pre.next = then;
then = start.next;
}
return dummy.next;
}
今天是周五。買了一臺iPhone。