Rotate List | Java最短程式碼實現
阿新 • • 發佈:2019-02-05
【思路】
1. 將尾指標指向頭指標
2. 並將head指標向後移動k = count – k % count - 1位,phead = head.next就是新連結串列的頭指標
3. 將head.next置空,並返回phead
public ListNode rotateRight(ListNode head, int k) { if (head == null) return head; ListNode phead = head; int count = 1; while (phead.next != null) { count++; phead = phead.next; } k = count - k % count - 1; phead.next = head; while (k-- > 0) head = head.next; phead = head.next; head.next = null; return phead; }
230 / 230 test
cases passed. Runtime: 1
ms Your runtime beats 14.33% of javasubmissions.
歡迎優化!