🌗 61. 旋转链表

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

🌗 61. 旋转链表

难度: 🌗

问题描述

img_1.png


解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        // 思路:
        // 求出链表长度,对 k 取余,截断数组,重新拼接
        int len = 0;
        ListNode cur = head;
        while(cur != null) {
            len ++;
            cur = cur.next;
        }
        if(len == 0) {
            return head;
        }
        k = k % len;
        if(k == 0) {
            return head;
        }
        // k > 0
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0; i < k; i ++) {
            fast = fast.next;
        }
        while(fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 截断 slow 和后面的节点
        ListNode next = slow.next;
        slow.next = null;
        fast.next = head;
        return next;
    }
}

输出

img.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou