Share my o(n) C++ simple and easy to understand


  • 0
    L
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) 
        {
            if(!head||!head->next)return head;
             deque<ListNode*> temp;
             ListNode *start=head,*end=head;
             int lth=0;
             while(start)
             {
                 lth++;
                 temp.push_back(start);
                 start=start->next;
             }
             start=head;
             k=k%lth;
             while(k--)
             {
                 end=temp.back();
                 temp.pop_back();
                 temp.push_front(end);
                 end->next=start;
                 start=end;
             }
             temp.back()->next=nullptr;
             return temp[0];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.