My C++ Solution


  • 2
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if (!head || !head->next) return head;
            int len = 0;
    		ListNode* temp = head;
    		while (temp){
    			++len;
    			temp = temp->next;
    		}
    		k = k%len;
    		ListNode* headNode = new ListNode(0);
    		headNode->next = head;
    		head = headNode;                        //insert head node
    		ListNode* prev = head;
    		ListNode* post = head;
    		while (prev->next){
    			if ((--k) < 0) post = post->next;
    			prev = prev->next;
    		}
    		if (post == head) return head->next;
    		prev->next = head->next;
    		head->next = post->next;
    		post->next = nullptr;
    		return head->next;
        }
    };

Log in to reply
 

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