題目
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->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
先得到鏈表長度len,n對len取余就是需要右轉長度(也可以不要長度,就是指針移動n次找到剪切位置,但是如果n過大就悲劇了),然後找到剪切位置,這裡依然用個哨兵簡化代碼。
代碼
public class RotateList { public ListNode rotateRight(ListNode head, int n) { if (head == null || n == 0) { return head; } ListNode tail = head; int len = 1; while (tail.next != null) { tail = tail.next; ++len; } n = len - n % len; if (n == len) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; for (int i = 0; i < n; ++i) { head = head.next; } tail.next = dummy.next; dummy.next = head.next; head.next = null; return dummy.next; } }