最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C语言数据结构旋转链表的实现
时间:2022-06-25 04:35:18 编辑:袖梨 来源:一聚教程网
实例:
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
分析:
感觉很直观,直接把分割点找出来就行,记得k可能大于len,要取模
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
classSolution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head,intk) {
// write your code here
if(head==NULL)
returnhead;
intlen = 0;
ListNode*temp = head;
while(temp)
{
len++;
temp = temp->next;
}
k%=len;
if(k==0)
returnhead;
k = len-k;
temp = head;
while(k>1)
{
temp = temp->next;
k--;
}
ListNode*newStart = temp->next;
temp->next = NULL;
temp = newStart;
while(temp->next)
temp = temp->next;
temp->next = head;
returnnewStart;
}
};
|
|
相关文章
- anthropic claude是什么 入门指南 + 应用场景 05-18
- pixiv官网登录入口直连-pixiv官网快捷登录通道 05-18
- 绝地求生41.1版本更新内容有哪些 05-18
- gemini3.0:完整指南 05-18
- 一耽漫画下载安卓最新版本-一耽漫画app官网入口免费安装 05-18
- openai api 价格 怎么收费?详解 05-18