61. Rotate List

本文介绍了一种链表旋转算法,该算法将链表向右旋转k个位置,并提供了详细的实现思路与C++代码示例。通过形成闭环的方式,有效地解决了链表旋转问题。

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

https://leetcode.com/problems/rotate-list/description/

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

  

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

在看答案之前 自己想了想 大致想法是对的

只是没有想到用环 这个solution很棒!

/**

* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        //k%length(listnode) 就是向前挪几个 
        //fist walk the list and get its length n, save the tail pre_pointer->tail_pre_pointer
        //then compute num = k % n(tail num should be move to the head)
        //index_key = n - num (from n - num to the last n-1 should be move to the head just in order)
        //find the pre_pointer of index_key -> key_pre_pointer
        //tail_pointer->next->next = head_pointer->next,head_pointer = ,key_pre_pointer->next = null key_pre_pointer。。。晕了
        // (以上是自己想法,没有想到用环,下面代码是最佳solution,用到了首尾相连的环 在这种不需要改变前后顺序的题目里面很适合用环 只改变首尾)


        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)
        }
        newH = tail->next; 
        tail->next = NULL;
        return newH;
    } 
};

https://leetcode.com/problems/rotate-list/discuss/22735/My-clean-C++-code-quite-standard-(find-tail-and-reconnect-the-list)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值