GuilinDev

Lc0061

05 August 2008

61 - Rotate List

原题概述

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

Example 1:

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

Example 2:

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

题意和分析

一个链表把右边k位的结点挪到左边来,可以分三步来做:1)计算链表长度;2)定位到len - k % len的位置因为k可能比len大,所有是k % len;3)在定位好的位置处开始rotate。

时间O(n),空间O(1)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;

        //找到链表的长度
        int len;
        for (len = 0; fast.next != null; len++) {
            fast = fast.next;
        }
        //定位到len - k%len的位置
        for (int i = 0; i < len - k%len; i++) {
            slow = slow.next;
        }

        //开始做rotation
        fast.next = dummy.next;
        dummy.next = slow.next;//把i-k%i的节点放到dummy之后(return后的第一位)
        slow.next = null;

        return dummy.next;
    }
}

也可以把链表弄成一个环来做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   public ListNode rotateRight(ListNode head, int k) {
      if (head == null || head.next == null) {
         return head;
      }

      ListNode index = head;
      int len = 1;
      while (index.next != null) {
         index = index.next;
         len++;
      }
      index.next = head;//形成环
      for (int i = 1; i < len - k % len; i++) {
         head = head.next;
      }
      ListNode result = head.next;

      head.next = null;//再断开环形成新的单链表

      return result;
   }
}