[LeetCode 题解]: Rotate List
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的长度没有说明,可能k比链表的长度还要大。 设链表的长度为Len,那么移动的节点个数应该为 K%Len.
class Solution { public:int getListLength(ListNode *head){int len=0;ListNode *tmp=head;while(tmp){len++;tmp = tmp->next;}return len;}ListNode *rotateRight(ListNode *head, int x) {if(head==NULL) return head; // empty listint len = getListLength(head);x = x%len; // how many nodes to rotateif( len<=1 || x==0) return head;// find xth node from tail of listListNode *tmp=head;ListNode *lend=head;ListNode *hstart=head;while(tmp->next){if(x==0){lend = lend->next;}else{--x;}tmp = tmp->next;}hstart = lend->next;lend->next=NULL;tmp->next=head;return hstart;} };
转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!
转载于:https://www.cnblogs.com/double-win/p/3883882.html
[LeetCode 题解]: Rotate List相关推荐
- 900 多道 LeetCode 题解,这个 GitHub 项目值得 Star!
转自 | 码农有道 大家好,我是小 G. 周末风和日丽,适合刷 LeetCode 今天给你们推荐个 GitHub 项目,里面收集了 900 多道 LeetCode 题解,并包含中英文两个版本,适合大多 ...
- PHP版Leetcode题解开始随缘更新
2019独角兽企业重金招聘Python工程师标准>>> PHP版Leetcode题解 我叫skys215,是一名bug工程师. 我接触编程的时间比较早,但是因为我数学不好加上比较懒, ...
- [LeetCode 题解]: Binary Tree Preorder Traversal
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a binary ...
- LeetCode 题解汇总
为什么80%的码农都做不了架构师?>>> LeetCode 题解汇总 转载于:https://my.oschina.net/michao/blog/801863
- leetcode题解【持续更新】
leetcode题解不断更新,以及nowcoder题解.一起加油! 完整请移步我的Github 转载于:https://juejin.im/post/5c8a73d8f265da2de80fa774
- 32位有符号整数_008. 字符串转换整数 (atoi) | Leetcode题解
点击上方"蓝色字体",选择"设为星标" 每天复习一道面试题,轻松拿大厂Offer~ 题目描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先 ...
- leetcode题解132-分割回文串 II
问题描述 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文. 返回符合要求的 最少分割次数 . 示例 1: 输入:s = "aab" 输出:1 解释:只需一次分割 ...
- leetcode题解131-分割回文串
问题描述 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 .返回 s 所有可能的分割方案. 回文串 是正着读和反着读都一样的字符串. 示例 1: 输入:s = "aa ...
- [LeetCode 题解]: Roman to Interger
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a roman ...
最新文章
- 关于HTML下overflow-y:auto无效、清除HTML默认边距、解决去除手机访问网页时的左右多余空白的三个方法汇总
- SQL 调试:无法启动 T-SQL 调试。未能附加到 SQL Server 进程
- python文件流读取二进制_Python使用web.py从POST请求中提取二进制文件
- 120万人同时在线考试,这么大的流量如何支撑
- SpringCloud微服务(03):Hystrix组件,实现服务熔断
- Spring处理log4j
- 使用Visual Studio 2010 Team System中的架构师工具(设计与建模)
- CSV 文件中的字段中的开头和结尾上,可能会存在空格或制表符,但是该如何处理呢?
- 【历史上的今天】9 月 30 日:“计算机之父”争夺战;Microsoft Excel 诞生;百度推出百度地图
- Matlab读取excel文件绘制折线图
- Javascript和C#正则只保留英文、数字、汉语、空格
- python导入包如果找不到
- python藏头诗生成器_藏头诗生成器
- JUC种常用的辅助类
- 【Lua基础系列】之热更新
- python从列表中随机抽取n个元素
- Ideas Of MySelf 20005-07-26
- mysql 事件报错1314_mysql 1314
- smartforms以PDF打印预览
- 凶猛现金贷背后的欲望深渊:女子网上撸81只猫,欠下70万元债