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

2022/2/7 6:13:57

本文主要是介绍腾讯五十题 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;
    }
}



这篇关于腾讯五十题 No.19旋转链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程