leetcode61——旋转链表

本文介绍了一种链表旋转算法的实现方法,通过寻找倒数第k个节点来完成链表的旋转,避免了使用递归所带来的额外开销,并提供了一段具体的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目;

思路:

最开始思路用递归

 但后面想到要多次到头结点 就达不到   就放弃递归

然后看评论区大佬第一条  说  其实就是倒数第k个移位即可

代码:

class Solution {
    ListNode pre;
    ListNode tem;
    int n=0;

    public ListNode rotateRight(ListNode head, int k) {
        if(k==0 || head==null ||head.next==null) return head;
        //常规递归不行 因为要往返几次
        // 将倒数第k 个作为 头 
        ListNode current=head;
        int count=1;//链表长度

        while(current.next!=null){
            current = current.next;
            ++count;
        }
        if(count<=k){//3  4
            k=k%count;
            //k=count%k;
        }
        if(k==0) return head;

        pre=head;
        head=rotate(head,k);
        return tem;
    }

    public ListNode rotate(ListNode head,int k){
        if(head==null){
            head=pre;
            return head;
        }
        head.next=rotate(head.next,k);//head.next=null  head  =5
        ++n;
        if(n==(k+1)){//n大于 链表长度时  
            tem=head.next;
            head.next=null;
            return head;
        }
        return head;
    }
}

不用方法  直接找到倒数第n个  返回

如下

ListNode current=head;
        int count=1;//链表长度

        while(current.next!=null){
            current = current.next;
            ++count;
        }
        if(count<=k){//3  4
            k=k%count;
            //k=count%k;
        }
        if(k==0) return head;

        //ListNode start=head;
        current.next=head;
        for(int i=0;i<count-k;i++){
            current=current.next;
        }

        ListNode newHead=current.next;

        current.next=null;
        return newHead;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值