腾讯五十题 No.19旋转链表

题目链接

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return null;
        int len = 1;
        ListNode tail = head;
        while(tail.next != null){
            len++;
            tail = tail.next;
        }//此刻tail已经是尾节点了

        // 3 - 4%3 = 2
        k = len-k%len;
        if(k==0) return head;

        //首尾相连
        tail.next = head;
        //1>=0 0>=0
        while(--k>=0){
            tail = tail.next;
        }
        
        head = tail.next;
        tail.next = null;
        return head;
    }
}

posted @   蹇爱黄  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示