leetcode 61 --Rotate List 链表 循环/断开 翻转
来源:互联网 发布:手机淘宝网的货到付款 编辑:程序博客网 时间:2024/06/03 16:44
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.
对于这题我们首先需要遍历链表,得到链表长度n,因为k可能大于n,所以我们需要取余处理,然后将链表串起来形成一个环,在遍历n - k % n个节点,断开,就成了。比如说,k等于2,我们遍历到链表结尾之后,连接1,然后遍历 5 - 2 % 5个字节,断开环,下一个节点就是新的链表头了。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||head.next==null||k==0) return head; ListNode curr=head; int len=1; while(curr.next!=null){ //循环跳出的时候指针指向最后一个元素 curr=curr.next; len++; } k=k%len; curr.next=head; for(int i=0;i<len-k;i++){ curr=curr.next; } head=curr.next; curr.next=null; return head; }}
1 0
- 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
- 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
- ( Leetcode 61 ) Rotate List
- leetcode-Rotate List-61
- PHP自学no00009数据类型浮点型之圆周率输出
- [从头学声学] 第207节 声学的原理
- CentOS系统时间与现在时间相差8小时解决方法
- 《Nodejs开发加密货币》之十:三张图让你全面掌握加密解密技术
- 趣闻段子开发中遇到的问题以及心得体会
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- 重置版内涵段子开发体会
- 2014 年最热门的国人开发开源软件 TOP 100
- module_platform_driver宏解析
- Android让Fragment加载到Activity中
- android studio无法关联源码
- 如何在Xcode中获取真机文件路径
- MySQL两种存储引擎MyISAM于InnoDB对比
- C++ 运算符重载