标签:style blog color io for div log amp sp
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.
思路:第一次遍历,计数链表中包含元素的总数n,同时找到最后一个元素;第二次遍历,直接找到第n-k个元素,然后交换前后两个链表。
1 class Solution { 2 public: 3 ListNode *rotateRight( ListNode *head, int k ) { 4 if( !head || !head->next ) { return head; } 5 ListNode *end = head; 6 int cnt = 1; 7 while( end->next ) { 8 end = end->next; 9 ++cnt; 10 } 11 k = cnt - k % cnt; 12 if( k == 0 ) { return head; } 13 ListNode *node = head; 14 while( --k > 0 ) { 15 node = node->next; 16 } 17 end->next = head; 18 head = node->next; 19 node->next = 0; 20 return head; 21 } 22 };
标签:style blog color io for div log amp sp
原文地址:http://www.cnblogs.com/moderate-fish/p/3935679.html