Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Created July 10, 2014 07:52
Show Gist options
  • Save walkingtospace/99aaf9abbe6021fbb811 to your computer and use it in GitHub Desktop.
Save walkingtospace/99aaf9abbe6021fbb811 to your computer and use it in GitHub Desktop.
rotate-list
https://oj.leetcode.com/problems/rotate-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
k=2
1->2->3->4->5
. .
1->2->3->4->5
. .
4->5->1->2->3
k=4;
1->2->3->4->5
. .
2->3->4->5->1
k=5;
1->2->3->4->5
..
//if first==second then return head
k=7(same as k=2);
1->2->3->4->5
. .
4->5->1->2>3
test cases
{}, 0
{1}, 1
{1,2}, 1
{1,2}, 2
{1,2}, 3
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(k <=0 || head == NULL) return head;
ListNode* first = head;
ListNode* second = head;
//shift k nodes
for(int i=0; i<k ; i++) {
second = second->next;
if(second == NULL) {
k -= i;
i = 0;
second = head;
}
}
if(head == second) return head;
while(second->next) {
first = first->next;
second = second->next;
}
second->next = head;
head = first->next;
first->next = NULL;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment