My accepted solution, 18ms


  • 0
    L
    /**
     * 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 == NULL)
                return head;
            ListNode* end = head;
            while (k--)
            {
                if (end->next == NULL)
                    end = head;
                else
                    end = end->next;
            }
            ListNode* beg = head;
            while (end->next)
            {
                end = end->next;
                beg = beg->next;
            }
            end->next = head;
            head = beg->next;
            beg->next = NULL;
            return head;
        }
    };
    

    Use two pointers traverse pointer 1 k times looping to head when it gets to the end. Start pointer two at the beginning, traverse until pointer one finds the end. Do three pointer swaps and done.


Log in to reply
 

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