Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 16, 2013 12:29
Show Gist options
  • Select an option

  • Save pdu/4966711 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4966711 to your computer and use it in GitHub Desktop.
Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. http://leetcode.com/onlinejudge#question_61
/**
* 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) {
ListNode * tmp = head;
ListNode * tail = head;
int cnt = 0;
while (tmp) {
tail = tmp;
tmp = tmp->next;
cnt++;
}
if (cnt == 0)
return NULL;
k = k % cnt;
if (k == 0)
return head;
else
cnt = cnt - k;
ListNode * ans = head;
ListNode * prev = NULL;
while (cnt--) {
prev = ans;
ans = ans->next;
}
if (prev)
prev->next = NULL;
if (tail)
tail->next = head;
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment