国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > Leetcode 61 Rotate List

Leetcode 61 Rotate List

来源:程序员人生   发布时间:2016-12-14 08:26:49 阅读次数:2115次

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.

将链表右移K位。

先遍历链表知道链表的长度,移动的位数会出现大于链表长度的情况,所以k=k%cnt

这样只要在cnt-k处断开链表,把后面的部份放在前脸部分的前面就得到新的链表了。

/** * 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) { ListNode* p=head; if(!p) return p; int cnt=1,cnt2=1; while(p->next!=NULL) { cnt++; p=p->next; } k%=cnt; if(k==0) return head; cnt-=k; ListNode* q=head; while(cnt2!=cnt) { cnt2++; q=q->next; } p->next=head; head=q->next; q->next=NULL; return head; } };


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生