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
.
answer:
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if(k == 0 ) return head; ListNode * PRe = head, * end = head; if(end == NULL || end->next == NULL) return head; int length = 1; while(k > 0){ while(end->next != NULL){ pre = end; end = end->next; length ++; } cout << length; if(k > length) k = k % length; if(k != 0){ end->next = head; pre->next = NULL; head = end; } k --; } return head; }};
新闻热点
疑难解答