Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 17, 2020 07:32
Show Gist options
  • Save JyotinderSingh/f91c411e29db478ab80403d1e9b9efdb to your computer and use it in GitHub Desktop.
Save JyotinderSingh/f91c411e29db478ab80403d1e9b9efdb to your computer and use it in GitHub Desktop.
Rotate List (LeetCode) | Interview Question Explanation
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
int n = 1;
auto tail = head;
while(tail->next) n++, tail = tail->next;
k %= n;
if(k == 0) return head;
auto new_tail = tail;
tail->next = head;
int steps_to_new_tail = n - k;
while(steps_to_new_tail--) new_tail = new_tail->next;
auto new_head = new_tail->next;
new_tail->next = nullptr;
return new_head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment