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.
Have you been asked this question in an interview?
这题之所以通过率不高是因为大家不知道怎么理解题意,其实就是反转k%n步就行了
这题之所以通过率不高是因为大家不知道怎么理解题意,其实就是反转k%n步就行了
- ListNode *rotateRight(ListNode *head, int k) {
- if(head==NULL)
- return NULL;
- int length=0;
- for(ListNode *p=head;p!=NULL;p=p->next)
- length++;
- k=k%length;
- if(k==0)
- return head;
- ListNode *p0=head;
- ListNode *p1=head;
- int i=0;
- for(;i<k && p1!=NULL;i++){
- p1=p1->next;
- }
- while(p1->next!=NULL){
- p0=p0->next;
- p1=p1->next;
- }
- ListNode *tmp=p0->next;
- p1->next=head;
- p0->next=NULL;
- return tmp;
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(3) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文详细解读了如何在面试中解决旋转链表的问题,包括理解题意、实现细节和代码示例。
212

被折叠的 条评论
为什么被折叠?



