Advertisement
nikunjsoni

61

Mar 19th, 2021
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* rotateRight(ListNode* head, int k) {
  14.         if(!head) return head;
  15.         int len = 1;
  16.         ListNode *newHead, *curr;
  17.         curr = newHead = head;
  18.         while(curr->next){
  19.             len++;
  20.             curr = curr->next;
  21.         }
  22.         curr->next = head;
  23.         if(k%=len){
  24.             for(int i=0; i<(len-k); i++)
  25.                 curr = curr->next;
  26.         }
  27.         newHead = curr->next;
  28.         curr->next = NULL;
  29.         return newHead;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement