题目

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

  1. Input: 1->2->3->4->5->NULL, k = 2
  2. Output: 4->5->1->2->3->NULL
  3. Explanation:
  4. rotate 1 steps to the right: 5->1->2->3->4->NULL
  5. rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

  1. Input: 0->1->2->NULL, k = 4
  2. Output: 2->0->1->NULL
  3. Explanation:
  4. rotate 1 steps to the right: 2->0->1->NULL
  5. rotate 2 steps to the right: 1->2->0->NULL
  6. rotate 3 steps to the right: 0->1->2->NULL
  7. rotate 4 steps to the right: 2->0->1->NULL

题意

依次将链表最后一个元素移到最前面,共移动k次。

思路

由于k可能大于链表本身长度length,所以先遍历一遍链表得到length,简化 k = k % length,再找到倒数k个元素前的一个元素(即新链表的最后一个元素),以此为分界点,将前半链表接到后半链表的后面。


代码实现

Java

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode rotateRight(ListNode head, int k) {
  11. if (k == 0 || head == null) {
  12. return head;
  13. }
  14. int length = 1;
  15. ListNode last = head;
  16. while (last.next != null) {
  17. length++;
  18. last = last.next;
  19. }
  20. k = k % length;
  21. if (k == 0) {
  22. return head;
  23. }
  24. // 找到新链表的尾结点
  25. int count = 1;
  26. ListNode newLast = head;
  27. while (count < length - k) {
  28. newLast = newLast.next;
  29. count++;
  30. }
  31. // 找到新链表的头结点,并将前半链表移到最后
  32. ListNode newHead = newLast.next;
  33. newLast.next = null;
  34. last.next = head;
  35. return newHead;
  36. }
  37. }

JavaScript

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @param {number} k
  11. * @return {ListNode}
  12. */
  13. var rotateRight = function (head, k) {
  14. if (!head || !k) return head
  15. let len = 1
  16. let last = head
  17. while (last.next) {
  18. len++
  19. last = last.next
  20. }
  21. k %= len
  22. if (!k) return head
  23. let p = head
  24. let count = len - 1
  25. while (count !== k) {
  26. p = p.next
  27. count--
  28. }
  29. let newHead = p.next
  30. p.next = null
  31. last.next = head
  32. return newHead
  33. }