[Linked List]Rotate List
Total Accepted: 55428 Total Submissions: 250727 Difficulty: Medium
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
.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getListLength(ListNode* head) { int len = 0; while(head){ len++; head = head->next; } return len; } ListNode* rotateRight(ListNode* head, int k) { int len = getListLength(head); k = len ==0 ? 0 : len - k%len ; if(head ==NULL || k==0 || k==len){ return head; } ListNode *newHead = NULL; ListNode *cur = head; int cnt =0 ; while(cur){ ++cnt; if(cnt == k){ newHead = cur->next; cur->next=NULL; break; } cur = cur->next; } ListNode* p=newHead; while(p && p->next){ p = p->next; } if(p){ p->next=head; } return newHead; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记