My 12ms c++ clean-code solution


  • 0
    J
     /**
     * 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;
            }
            
            if (k == 0)
            {
                return head;
            }
            
            int count = 0;
            {
                ListNode* cur = head;
                while(cur != NULL)
                {
                    count++;
                    cur = cur->next;
                }
            }
            
            k = k % count;
            
            if (k == 0)
            {
                return head;
            }
            else
            {
                ListNode* pre = NULL;
                ListNode* cur = head;
                ListNode* newHead = NULL;
                
                for (int i = 0; i < count - k; i++)
                {
                    pre = cur;
                    cur = cur->next;
                }
                
                pre->next = NULL;
                
                newHead = cur;
                
                while(cur != NULL)
                {
                    pre = cur;
                    cur = cur->next;
                }
                
                pre->next = head;
                
                return newHead;
            }
        }
    };

Log in to reply
 

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