【LeetCode】61. Rotate List(C++)

地址:https://leetcode.com/problems/rotate-list/

题目:

Given a linked list, rotate the list to the right by k k places, where k 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

理解:

把一个链表向右旋转k次,也就是把倒数第k个结点当作头结点。需要改变的有尾结点的next域,倒数第k+1个结点的next域和head。

实现:

下面的实现非常优雅。
使用tail进行操作,tail就是head的前一个,因此可以写for(int i=0;i<cnt-k;++i)
tail->next=head;就直接改变了尾节点的next

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return nullptr;
        int cnt=1;
        ListNode* tail=head;
        while(tail->next){
            tail=tail->next;
            ++cnt;
        }
        tail->next=head;
        if(k%=cnt){
            for(int i=0;i<cnt-k;++i){
                tail=tail->next;
            }
        }
        head=tail->next;
        tail->next=nullptr;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84745498