C++ code use two pointer and dummy head.


  • 0
    class Solution {
    public:
      ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL || k == 0)
        {
          return head;
        }
        ListNode *dummy = new ListNode(-1);
        dummy -> next = head;
        ListNode *fast = head, *slow = head;
        int listCount = countListLength(head);
    
        k %= listCount;
    
        while (k --)
        {
          fast = fast -> next;
        }
    
        while (fast -> next)
        {
          fast = fast -> next;
          slow = slow -> next;
        }
    
        if (slow -> next == NULL)
        {
          return head;
        }
        dummy -> next = slow -> next;
        fast -> next = head;
        slow -> next = NULL;
        return dummy -> next;
      }
      int countListLength(ListNode *head)
      {
        int count = 0;
        while (head != NULL)
        {
          head = head -> next;
          count ++;
        }
        return count;
      }
    };
    

Log in to reply
 

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