Leetcode61 Rotate List

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24634505/article/details/81024124

题目描述

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

思路

虽然旋转的步骤是一次一次完成的,但从结果来看就是将链表的两段交换顺序拼接,因此还是借助两个指针找到链表的尾部和要截断的位置,将第一部分接到第二部分后面。
注意:
1、空链表。
2、旋转次数是链表长度倍数的链表。
3、对链表长度取模减少重复运算,以通过旋转次数巨大的测试用例。取模后注意余数为0的情况的处理。

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(k==0||head==NULL||head->next==NULL)return head;

        ListNode*p=head;
        ListNode*q=head;
        int len=0;
        while(k--)
        {
            p=p->next;
            len++;
            if(p==NULL)
            {
                if(k==0||k%len==0)
                  return head;
                else{
                    p=head;
                    k=k%len;
                }
            }
        }

        while(p->next)
        {
            p=p->next;
            q=q->next;
        }

        ListNode*res=q->next;
        q->next=NULL;
        p->next=head;
        return res;
    }
};

这里写图片描述
(。・∀・)ノ゙嗨!伊利亚大陆的朋友们,今天过的怎么样~?

猜你喜欢

转载自blog.csdn.net/qq_24634505/article/details/81024124
今日推荐