加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Leetcode 61 Rotate List

发布时间:2020-12-13 21:18:13 所属栏目:PHP教程 来源:网络整理
导读: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

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; } };


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读