[LeetCode] Rotate List 解题报告

本文介绍了一种链表操作——右旋。通过计算链表长度并调整指针连接,实现链表的旋转。提供了完整的C/C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

» Solve this problem

[解题思路]

首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针, 将整个圈连起来,接着往前跑len – k%len,从这里断开,就是要求的结果了。
[Code]
1:    ListNode *rotateRight(ListNode *head, int k) {  
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: if(head == NULL || k ==0) return head;
5: int len =1;
6: ListNode* p = head,*pre;
7: while(p->next!=NULL)
8: {
9: p = p->next;
10: len++;
11: }
12: k = len-k%len;
13: p->next = head;
14: int step =0;
15: while(step< k)
16: {
17: p = p->next;
18: step++;
19: }
20: head = p->next;
21: p->next = NULL;
22: return head;
23: }

[Note]
注意K大于len的可能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值