[leetcode]61. Rotate List

本文介绍了一种使用循环链表实现列表旋转的高效算法。通过计算距离新头部节点的距离,可以将复杂度降低到O(n),并展示了具体的实现代码。

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

忘记哪一题了,反正和前面有一题很像,挺简单的

Solution 1: 利用循环链表O(n)

int dis=count-k%count;
利用这个式子,将问题转换为–找新的head node即可

/**
 * 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 is null or k=0, we simply return head;
        if(head==null||k==0)return head;
 
        ListNode p=head;
        int count=0;
        //p points to the last node when loop ends
        while(p.next!=null){
            count++;
            p=p.next;
        }
        // in the loop above, when p points to the last node, p.next==null
        // so the last node didn't count++, we now manually count++;
        count++;
       //we calculate the distance we need to move to the new head
        int dis=count-k%count;
        
        // make the last node point to head, which makes this list a  cicular list
        p.next=head;
        //we use q to move from head
        ListNode q=head;
     
     //q now moves to a  node exactly before the new head node 
        for(int i=0;i<dis-1;i++){
            q=q.next;
        }
        //p now points to the new head node 
        p=q.next;
        // so now q is the last node of the new list
        // we set the next field of the last node as null
        q.next=null;
	//return the new head 
        return p;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值