LeetCode | 61. Rotate List

本文介绍了一种链表操作算法——链表旋转。该算法能够高效地将链表的末端K个元素移至链表的头部,并提供了两种实现方法。一种是通过新建头尾节点并进行指针调整;另一种则是构建循环链表再进行计数切割。

摘要生成于 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.

题意:将链表的右端的K个元素放到左边。

// 16 ms
/**
 * 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) {
        //处理空链表
        if(head == NULL)
            return head;

        int len = 0;
        ListNode* it = head;
        while(it)
        {
            it = it->next;
            len++;
        }
        k %= len;

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

        it = head;
        while(it->next)
            it = it->next;
        ListNode *NewHead = head, *NewTail = head;
        for(int i=0;i<len-k-1;i++)
            NewTail = NewTail->next;
        NewHead = NewTail->next;
        NewTail->next = NULL;       //顺序很重要
        it->next = head;

        return NewHead;
    }
};

附:solution区解法。先构成一个循环链表,然后直接从结尾开始计数,直到停止。

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)
        }
        newH = tail->next;
        tail->next = NULL;
        return newH;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值