Rotate List
来源:互联网 发布:知乎搜索引擎地址 编辑:程序博客网 时间:2024/05/17 09:36
题目链接:
https://leetcode.com/problems/rotate-list/description/
描述
Given a list, rotate the list to the right by k places, where k is non-negative.
输入
Given 1->2->3->4->5->NULL and k = 2,
输出
return 4->5->1->2->3->NULL.
样例输入
样例输出
算法思想:
此题就是要把后面的k位数移到链表头即可,目的就是找在哪里移动,思想先把链表变成环,然后找切割点即可。需要注意的是对于K大于链表长度大小的情况 取模一下即可
比如【312】当k=5的时候,输出应该为【123】等于k=k%(链表大小)时的结果
源代码
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || k == 0) return head; ListNode *tem = head; ListNode *tem2; int num = 1; while (tem->next) { num++; tem = tem->next; } if (k > num) { k = k % num; } tem->next = head; //让链表成环 //找切割点 int pre = num - k; while (pre--) tem = tem->next; head = tem->next; tem->next = NULL; return head; }};
最优源代码
算法复杂度:
阅读全文
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- TP5 基础说明
- LabVIEW 程序的内存优化
- 34嘻刷刷
- Android 实现圆角按钮(selector和shape的简单用法)
- Linux 的crontab定时任务进行接口调用
- Rotate List
- BigDecimal和NumberFormat四舍五入的区别
- vue编程式导航
- java中的抽象类
- sudo sh -c 'echo 4 > test_rw'
- spring-bean的作用域
- Java设计模式--状态模式【State Pattern】
- 进程和线程的区别
- css的一些问题与细节