欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode61. 旋转链表

程序员文章站 2022-05-06 09:39:33
...

leetcode61. 旋转链表

/**
 * 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 == nullptr || head->next == nullptr)
        {
            return head;
        }
        vector<int> v;
        while(head)
        {
            v.push_back(head->val);
            head = head->next;
        }
        vector<int> temp = v;
        for(int i = 0; i < temp.size(); i++)
        {
            v.push_back(temp[i]);
        }
        int len = k % temp.size();
        vector<int> res;
        for(int i = temp.size() - len; i < temp.size() - len + temp.size(); i++)
        {
            res.push_back(v[i]);
        }
        ListNode* r = new ListNode(0);
        ListNode* dummynode = r;
        for(int i = 0; i < res.size(); i++)
        {
            dummynode->val = res[i];
            if(i == res.size() - 1)
            {
                break;
            }
            dummynode->next = new ListNode(0);
            dummynode = dummynode->next;
        }
        return r;
    }
};