leetcode题解-61. Rotate List
来源:互联网 发布:在线dns检测优化 编辑:程序博客网 时间:2024/06/03 23:49
61,题目:
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值可能比链表总长度还要大,这就会带来一定的麻烦。为了方便起见,我们可以先遍历链表,获取链表的总长度,然后将链表首尾相连编成一个环,这样做的好处是我们可以很容易获得要反转的位置,然后在该处将链表截断即可。代码入下:
public ListNode rotateRight1(ListNode head, int k) { if(head==null||head.next==null||k==0) return head; //获取链表的总长度 ListNode index=head; int len=1; while(index.next!=null) {index=index.next; len++;} //将链表首尾相连形成环 index.next=head; //找到需要截断的位置,因为k可能大于链表总长度。所以这里使用取余操作 for(int i=0;i<len-k%len;i++) { index=index.next; } //将该处截断,指向空指针即可 ListNode result=index.next; index.next=null; return result; }
阅读全文
0 0
- leetcode题解-61. Rotate List
- leetcode题解-61. Rotate List
- LeetCode题解:Rotate List
- LeetCode题解-61-Rotate List
- LeetCode 题解(37): Rotate List
- LeetCode题解——Rotate List
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- yii2.0--reseful实现
- Java第二天,mysql安装
- js的面向对象(通俗解说)
- 009-冲动基因|为什么会有人选择冒险
- [IOS APP]翟鸿燊演讲精选-有声国学系列1
- leetcode题解-61. Rotate List
- kaggle干货
- OFFICE OLE2LINK(CVE-2017-0199)漏洞利用详解
- SQL server 登录名与用户名
- tr或者td里没有id,如何取固定的某一tr或者td?
- 文本情感分类
- linux常用基本命令
- Tensorflow实现CNN网络
- day08&09-通知机制(QQ聊天界面&QQ好友列表)