LeetCode61- 旋转链表

LeetCode61- 旋转链表

最近全国疫情严重,待在家里没事干,马上又要准备春招了,最近刷刷题,记录一下!再说一句,武汉加油,大家出门记得戴口罩!

1、题目

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

2、思路

在这里插入图片描述
在这里插入图片描述

3、代码

c++

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return NULL;
        //计算链表长度
        int n=0;
        for(auto p=head;p;p=p->next)  n++//对k取模
        k%=n;
        auto first=head,second=head;
        //first指针先走K步
        while(k--)    first=first->next;
        //first、second指针同时前进,直到尾部为止
        while(first->next)
        {
            first=first->next;
            second=second->next;
        }
        //first指针指向头结点、secode的下个元素成为头结点,second指针指向null
        first->next=head;
        head=second->next;
        second->next=NULL;
        return head;     
    }
};

Java

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(!head) return null;
        for(ListNode p=head;p;p=p.next)  n++;
        k%=n;
        ListNode first=head,second=head;
        for(int i=1;i<=k;i++)
        {
            first=first.next;
        }
        
        while(first.next!=null)
        {
            first=first.next;
            second=second.next;
        }
        first.next=head;
        head=second.next;
        second.next=null;
        return head;   
    }
}
发布了38 篇原创文章 · 获赞 46 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sk18192449347/article/details/104100510
今日推荐