您的位置:首页 > 其它

leetcode之Rotate List

2013-09-18 08:59 330 查看
/**

* 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) {

// Start typing your C/C++ solution below

// DO NOT write int main() function

if (head==NULL||k<0) {

return head;

}

ListNode* end=head;

int len=1;

while(end->next) {

end=end->next;

len++;

}

if (k>=len) {

k=k%len;

}

if (k==0) {

return head;

}

ListNode* pos=head;

ListNode* pr=head;

while(pos&&k>0) {

k--;

pos=pos->next;

}

if (k>0) {

return head;

}

while(pos->next) {

pos=pos->next;

pr=pr->next;

}

ListNode* phead=pr->next;

pr->next=NULL;

end->next=head;

return phead;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: