92. Reverse Linked List II - Medium
阿新 • • 發佈:2018-12-15
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
只反轉從m到n的部分連結串列
M1: iterative
首先找到prev的位置(開始反轉位置的前一個節點),cur為prev的後一個節點。然後開始反轉,迴圈n-m次,在迴圈裡,prev的位置始終保持不變,先儲存cur下一個節點的位置,即nextnode,cur指向nextnode的下一個節點,nextnode指向prev的下一個節點,prev指向nextnode。
e.g.
1->2->3->4->5->NULL 2->4, 3->2, 1->3 => 1->3->2->4
p c n
1->3->2->4->5->NULL 2->5, 4->3, 1->4 => 1->4->3->2->5
p c n
1->4->3->2->5->NULL
p c n
time: O(n), space: O(1)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { int len = n - m; ListNode dummy= new ListNode(0); dummy.next = head; ListNode prev = dummy, cur = dummy.next; while(m > 1) { // find prev prev = prev.next; cur = cur.next; m--; } // return prev; while(len > 0) { ListNode nextnode = cur.next; cur.next = nextnode.next; nextnode.next = prev.next; prev.next = nextnode; len--; } return dummy.next; } }