1. 程式人生 > >Rotate List LeetCode Java

Rotate List LeetCode Java

可能 節點 lis color AC next 因此 slow new

描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example: Given 1->2->3->4->5->nullptr and k = 2, return 4->5->1->2->3->nullptr.
分析
先遍歷一遍,得出鏈表長度 len,註意 k 可能大於 len,因此令 k% = len。將尾節點 next 指針
指向首節點,形成一個環,接著往後跑 len ? k 步,從這裏斷開,就是要求的結果了。

代碼

 1
public static ListNode rotateRight(ListNode head, int n) { 2 if (head == null || head.next == null || n == 0) 3 return head; 4 ListNode fast = head, slow = head, countlen = head; 5 ListNode newhead = new ListNode(-1); 6 int len = 0; 7 8 while
(countlen != null) { 9 len++; 10 countlen = countlen.next; 11 } 12 13 n = n % len; 14 if (n == 0) 15 return head; 16 for (int i = 0; i < n; i++) { 17 fast = fast.next; // slow與fast間隔n+1 18 } 19 while (fast.next != null
) { 20 slow = slow.next; // slow指向要倒著數的開始點的前一個位置。 21 fast = fast.next; 22 23 } 24 25 newhead = slow.next; 26 fast.next = head; 27 slow.next = null; 28 29 return newhead; 30 }

Rotate List LeetCode Java