61. Rotate List

本文介绍了一种链表操作算法——链表右旋转。通过将链表尾部的若干元素移至头部实现。提供了两种实现方式,包括求解链表长度及尾节点的方法,并通过调整指针完成链表的旋转。

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

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


  • 思路

先求出尾节点以及链表大小,然后重新连接,感觉链表的链接还是很直观的。

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {

        if(k==0 || !head)
            return head;

        ListNode* tail=head;//用来指向尾节点
        ListNode* curr=head;//用来指向K之前的节点
        int size=1;         //用来记录链表的大小


        while(tail->next)//让tail指向尾节点
        {
            tail = tail->next;
            size++;
        }

        tail->next = head;//让尾节点指向头节点

        k = k%size;       //防止K大于size
        int n=size-k-1;   //计算循环几次可以到K之前的节点

        while(n)          //使curr指向K之前的节点
        {
            curr = curr->next;
            n--;
        }

        head = curr->next; //修正头节点
        curr->next = NULL; //修正新尾节点指向NULL

        return head;
    }
};

简化版

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;

        int len=1; // number of nodes
        ListNode *newH, *tail;
        newH=tail=head;

        while(tail->next)  // get the number of nodes in the list
        {
            tail = tail->next;
            len++;
        }
        tail->next = head; // circle the link

        if(k %= len) 
        {
            for(auto i=0; i<len-k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)//从尾部开始的循环所以不用再-1
        }
        newH = tail->next; 
        tail->next = NULL;
        return newH;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值