Leetcode学习之路

Leetcode 学习之路 061 旋转链表

题目描述

       给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
在这里插入图片描述

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

一、算法描述

       对于旋转链表直接使用暴力解法,使时间复杂度为 O ( N 2 ) O(N^2) O(N2),并且在Leetcode提交时会显示超时。所以一种降低时间复杂度的算法为,将链表的尾节点与头节点相连,构成循环链表,进行旋转操作时候并不需要真正移动每一个链表中的元素,而是将移动次数转为计算尾节点的位置,具体公式为
        i n d e x = l e n g t h − 1 − k % l e n g t h index=length-1-k\%length index=length1k%length
       当找到尾节点,则需要建立新的头节点,并且将循环链表断开。

result=index.next
index.next=null

二、JAVA实现

public ListNode rotateRight(ListNode head, int k){

        if (head==null||head.next==null) return head;
        int n=1;
        ListNode temp=head;
        while (temp.next!=null){
            temp=temp.next;
            n++;
        }
        int last=k%n;
        if (last==0) return head;//移动链表的整数倍
        temp.next=head;
        temp=head;
        for (int i=0;i<n-1-last;i++)
            temp=temp.next;
        ListNode result=temp.next;
        temp.next=null;
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值