Leetcode-61: 旋转链表

题目链接

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

题目

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例

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

 示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示

  • 链表中节点的数目在范围 [0, 500] 内
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^{9}

思路一

先用数组储存所有元素,再重新赋值。

C++ Code

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        //用数组存放 取的时候从每个位置+k取 +k后大于n取余
        if(!head) return head;
        vector<int> L;
        ListNode* cur=head;
        while(cur) 
        {
            L.push_back(cur->val);
            cur=cur->next;
        }
        int n=L.size();
        int i=0;
        cur=head;
        if(k>n) k=k%n;
        while(cur)
        {
            if(i-k>=0) cur->val=L[i-k];
            else cur->val=L[n+(i-k)];
            i++;
            cur=cur->next;
        }  
        return head;
    }
};

思路二

首位相连,形成环,再找新的头结点断开。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        //先找到尾,再找切开的节点
        if(!head)return head;
        ListNode* tail=head;
        ListNode* pre;
        int length=1;
        while(tail->next){
            //找到结尾和节点个数
            length++;
            tail=tail->next;
        }
        
        int step=k%length;
        if(step==0)return head;
        tail->next=head;
        while(length-step){
            length--;
            pre=head;
            head=head->next;
        }
        pre->next=nullptr;
        return head;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值