标签:style blog http color io os ar for 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
.
思路:将单链表首尾相连呈环状,再在适当位置断开,具体于代码中;
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(!head) return head; int length=1; ListNode *cur=head; while(cur->next) { ++length; cur=cur->next; } //become a circle cur->next=head; int count=1; cur=head; ListNode *ltcur; while(cur) { //using remained:important if(count==length-k%length) { ltcur=cur; break; } ++count; cur=cur->next; } //new head cur=ltcur->next; //break the circle ltcur->next=NULL; return cur; } };
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/chengyuz/p/4052734.html