- Total Accepted: 96273
- Total Submissions: 399212
- Difficulty: Medium
- Contributors: Admin
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
.
分析
这里题目的 test case 有一个没有说清楚的条件,就是当 k > list.size ,怎么处理, 实际上题目是取模的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public : /** * p t * dummy->1->2->3->4->5->NULL , k = 2 */ ListNode* rotateRight(ListNode* head, int k) { if (k == 0 || head == NULL) return head; int len = 0; ListNode dummy(0); ListNode* tail = head; ListNode* pos = &dummy; dummy.next = head; while (tail != NULL){ tail = tail->next; ++len; } k = k % len; if (k == 0) return head; tail = head; while (--k){ tail = tail->next; } while (tail->next != NULL){ pos = pos->next; tail = tail->next; } tail->next = dummy.next; head = pos->next; pos->next = NULL; return head; } }; |