LeetCode 61

https://leetcode-cn.com/problems/rotate-list/

这个题我先谈谈我自己的想法,先用快慢指针寻找向右移动第k次后的链表的头,然后让原链表的尾指向头,直接返回新的链表头即可,但是这样出现如果k比原链表长度大的情况,就是用判断,如果出循环后i不等于k,说明链表长度短了,需要重新判断。

判断方法为:如果k是链表长度的整数倍,直接返回原链表,否则的话就对原链表执行向右旋转k%i个位置的操作,i为链表长度。这样做打败79%的人。

/**
 * 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 || k == 0){
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = head;
        ListNode slow = head;
        int i = 0;
        while(fast.next != null){
            if(i < k){
                fast = fast.next;
                i++;
                continue;
            }
            fast = fast.next;
            slow = slow.next;
        }
        if(i != k){
            if(k % (i+1) == 0){
                return dummy.next;
            }else{
                return rotateRight(dummy.next, k%(i+1));
            }
        }else{
            ListNode newHead = slow.next;
            slow.next = null;
            fast.next = dummy.next;
            return newHead;
        }
    }
}
View Code

后来一看评论区,发现我的解法还是too young。直接统计链表的长度,然后让他们首尾相连,在第k%i(i为链表长度)的地方断开,返回断开的下一个结点就可以了。

我是真的菜 TvT

原文地址:https://www.cnblogs.com/ZJPaang/p/12755407.html