61.旋转链表

1.题目描述

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

示例 1:

img

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

示例 2:

img

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

2.解题过程

首先遍历链表,获得链表的长度count,然后将链表尾部的next指向头部,形成一个环;接着向右移动count - k % count的长度,将链表断开,返回断开后的头节点即可。

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int count = 1;
        ListNode cursor = head;
        while (cursor.next != null) {
            cursor = cursor.next;
            count++;
        }

        int countDown = count - k % count;

        cursor.next = head;
        while (countDown > 0) {
            cursor = cursor.next;
            countDown--;
        }

        ListNode ret = cursor.next;
        cursor.next = null;
        return ret;
    }
}

results matching ""

    No results matching ""