leetcode 61旋转链表

做到目前最难的一个题,大意了,思路上没问题,但是效率太差,最后的结果就是超时,其实首先确定那个节点将是下一个链表的新节点,就能很简单的解决战斗,下面贴代码

/**
 * 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(!k || !head || !head->next) 
        {
            return head;
        }
        int i = 1 ;
        ListNode* temp = head;
        ListNode* temp1 = head;
        ListNode* temp2 =new ListNode(0,head);
        while(temp->next)
        {
            temp = temp->next;
            i++;
        }
        int j = k % i;
        if(!j)
        {
            return head;
        }
        for(int l = 0 ; l < i-j ; l++)
        {
            temp1 = temp1->next;
            temp2 = temp2->next;
        }
        temp->next = head;
        temp2->next = NULL;
        head = temp1;
        return head;
    }
};

 

posted @ 2021-02-12 14:25  zhaohhhh  阅读(62)  评论(0)    收藏  举报