【做题也是一场游戏】61. 旋转链表

173 阅读1分钟

题目地址

leetcode-cn.com/problems/ro…

题目描述

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。 

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

题解

其实就是将后面 nn 个节点移到前面

可以将首尾闭合,找到这个需要作为新首节点的节点,然后断开和上个节点的连接

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        iter.next = head;
        while (add-- > 0) {
            iter = iter.next;
        }
        ListNode ret = iter.next;
        iter.next = null;
        return ret;
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),最坏情况下,我们需要遍历该链表两次。
  • 空间复杂度:O(1)O(1),我们只需要常数的空间存储若干变量。