Given a list, rotate the list to the right by k
places, where k is non-negative.
Example
Given 1->2->3->4->5
and k = 2
, return 4->5->1->2->3
.
解法一:
1 public class Solution { 2 private int getLength(ListNode head) { 3 int length = 0; 4 while (head != null) { 5 length ++; 6 head = head.next; 7 } 8 return length; 9 } 10 11 public ListNode rotateRight(ListNode head, int n) { 12 if (head == null) { 13 return null; 14 } 15 16 int length = getLength(head); 17 n = n % length; 18 19 ListNode dummy = new ListNode(0); 20 dummy.next = head; 21 head = dummy; 22 23 ListNode tail = dummy; 24 for (int i = 0; i < n; i++) { 25 head = head.next; 26 } 27 28 while (head.next != null) { 29 tail = tail.next; 30 head = head.next; 31 } 32 33 head.next = dummy.next; 34 dummy.next = tail.next; 35 tail.next = null; 36 return dummy.next; 37 } 38 }
快慢指针 + dummy节点,参考@NineChapter 的代码
解法二:
1 class Solution { 2 public: 3 /** 4 * @param head: the list 5 * @param k: rotate to the right k places 6 * @return: the list after rotation 7 */ 8 ListNode *rotateRight(ListNode *head, int k) { 9 if (head == NULL) { 10 return head; 11 } 12 13 int len = 0; 14 for (ListNode *node = head; node != NULL; node = node->next) { 15 len++; 16 } 17 k = k % len; 18 19 if (k == 0) { 20 return head; 21 } 22 23 ListNode *fast = head; 24 for (int i = 0; i < k; i++) { 25 fast = fast->next; 26 } 27 28 ListNode *slow = head; 29 while (fast->next != NULL) { 30 slow = slow->next; 31 fast = fast->next; 32 } 33 34 fast->next = head; 35 head = slow->next; 36 slow->next = NULL; 37 38 return head; 39 } 40 };
不带dummy节点的解法,参考@NineChapter 的代码