LeetCode刷题笔录 Rotate List
来源:互联网 发布:百度地图js touchend 编辑:程序博客网 时间:2024/06/05 00:10
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
.
这题想法就是用两个pointer,一个比另外一个领先k个位置。对于上面那个例子,初始p1=1,p2=3;结束时p1=3,p2=5。
先扫描一遍链表,得到链表的长度,然后用k = n % length得到实际需要rotate的长度。
特殊情况:
1.list是空的
2.k=0
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null) return null; //get the length of the list ListNode p1 = head; int length = 1; while(p1.next != null){ length++; p1 = p1.next; } //get the rounded amount to rotate int k = n % length; //if k is zero, return as is if(k == 0) return head; //use two pointers with k distance p1 = head; ListNode p2 = head; for(int i = 0; i < k; i++){ p2 = p2.next; } while(p2.next != null){ p1 = p1.next; p2 = p2.next; }//the new head pointer is p1.next p2 = head; ListNode newHead = p1.next; p1.next = null; ListNode p3 = newHead; while(p3.next != null){ p3 = p3.next; } p3.next = p2; return newHead; }}
可以优化一下:
第一遍跑到尾巴得到长度以后,直接p2.next = head,把尾巴和头连起来,然后再跑length - k长度,把next设置成null即可。这样少了一次扫描,也不用考虑k=0的情况了。
0 0
- LeetCode刷题笔录 Rotate List
- LeetCode刷题笔录 Reorder List
- LeetCode刷题笔录Linked List Cycle
- LeetCode刷题笔录Partition List
- LeetCode刷题笔录Sort List
- LeetCode刷题笔录Remove Duplicates From Sorted List
- LeetCode刷题笔录Linked List Cycle II
- LeetCode刷题笔录Flatten Binary Tree to Linked List
- LeetCode刷题笔录Reverse Linked List II
- LeetCode刷题笔录Remove Duplicates from Sorted List II
- [leetcode刷题系列]Rotate List
- [leetcode][list] Rotate List
- Leetcode刷题笔录 Anagrams
- LeetCode刷题笔录 Permutaions
- LeetCode刷题笔录Combinations
- LeetCode刷题笔录Subsets
- LeetCode刷题笔录Triangle
- LeetCode刷题笔录LRUCache
- SQL Developer 警告--无法安装某些模块
- Android菜单学习
- leetcode 第10题 Regular Expression Matching
- ubuntu 12.04 alt+tab无法切换窗口的问题
- Samples of PL/SQL in JDBC
- LeetCode刷题笔录 Rotate List
- TFS清除不同用户组的工作状态
- volatile关键字
- Linux命令之查找
- python二维码库pyqrcode-0.2.1安装使用
- 批处理
- C++小知识之指针和引用的区别
- ASP.NET 递归将分类绑定到 TreeView
- Java中4种类型的内部类