Leetcode 61 Solution

This article provides solution to leetcode question 61 (rotate-list)

https://leetcode.com/problems/rotate-list

Solution

/** * 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) { if (head == NULL) return NULL;
int n = 0; ListNode* p = head; ListNode* tail = head;
while (p) { tail = p; p = p->next; n++; }
p = head; k = k % n;
if (k == 0) return head;
ListNode* curr = NULL;
for (int i = 0; i < n - k; i++) { curr = p; p = p->next; }
ListNode* newhead = curr->next;
curr->next = NULL; tail->next = head;
return newhead; } };