leetcode并查集,[LeetCode]Rotate List

 2023-12-06 阅读 35 评论 0

摘要: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. 思考:先首尾連成環,head前進(len-k%len)步,拆環

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.

思考:先首尾連成環,head前進(len-k%len)步,拆環。

/*** 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==NULL||k==0) return head;ListNode *p=head;int len=1;while(p->next){len++;p=p->next;}p->next=head;k%=len;int step=len-k;while(step--){p=p->next;}head=p->next;p->next=NULL;return head;}
};

leetcode并查集。  

?

轉載于:https://www.cnblogs.com/Rosanna/p/3516145.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/192824.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息