标签:
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
.
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || k <= 0) return head; //get length ListNode *temp = head; int node_count = 0; while(temp != NULL) { node_count++; temp = temp->next; } if(k > node_count) k = k%node_count; if(k == node_count || k == 0) return head; //first node move k step ListNode *first = head; while( k > 0) { first = first->next; k--; } //when first node move to last, the second node move (length - k) step ListNode *second = head; while(first->next != NULL) { first = first->next; second = second->next; } ListNode *newhead = second->next; //be a circle first->next = head; //broken circle second->next = NULL; return newhead; } };
class Solution { public: ListNode* getLastNode(ListNode *head, int& len){ ListNode* node = head; len = 1; if(head == NULL){ len = 0; return NULL; } while( node->next != NULL){ node = node->next; len++; } return node; } ListNode *rotateRight(ListNode *head, int k) { if(head == NULL){ return head; } int len; ListNode* lastNode = getLastNode(head, len); lastNode->next = head; k %= len; int step = len - k; while(step>0){ lastNode = lastNode->next; step--; } head = lastNode->next; lastNode->next = NULL; return head; } };
标签:
原文地址:http://blog.csdn.net/fox64194167/article/details/44086895