Skip to content

Commit

Permalink
Create rotateListCpp
Browse files Browse the repository at this point in the history
  • Loading branch information
striver79 authored Oct 1, 2021
1 parent 2877cd8 commit 3706cbe
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions rotateListCpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 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) {
// edge cases
if (!head || !head->next || k == 0) return head;

// compute the length
ListNode *cur = head;
int len = 1;
while (cur->next && ++len)
cur = cur->next;

// go till that node
cur->next = head;
k = len - k % len;
while (k--) cur = cur->next;

// make the node head and break connection
head = cur->next;
cur->next = NULL;


return head;
}
};

0 comments on commit 3706cbe

Please sign in to comment.