C++ solution


  • 0
    F

    /**

    • 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 || head->next == NULL|| k == 0)
      {
      return head;
      }

       int n = 1;
       ListNode* phead = head;
       
       while(phead->next != NULL)
       {
           phead = phead->next;
           n++;
       }
       
       k = k % n;
       if(k == 0)
       {
           return head;
       }
       
       phead->next = head;
       
       int m = n-k-1;
       
       while(m > 0 )
       {
           head = head->next;
           m--;
       }
       phead = head;
       head = head->next;
       phead->next = NULL;
       
       return head;
      

      }
      };


Log in to reply
 

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