LeetCode 061 Rotate List
来源:互联网 发布:淘宝lol代练可靠吗 编辑:程序博客网 时间:2024/05/01 20:06
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个节点,来旋转链表。
1 基本思路。普遍使用的dummynode ,还有pre,cur 两个来表示前后节点。一开始先test往后k格;之后cur和test同时移动,当test为null时,cur即为新的头节点。此时要做些操作,pre.next要为null,新的head为cur。之后到链表最后,接上原来的头节点即可,dummynode发挥用处。代码如下:
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(n<=0 || head == null|| head.next==null) { return head; } ListNode dummynode = new ListNode(Integer.MIN_VALUE); dummynode.next = head; ListNode test =head; while(n>0){ if(test==null){ test=head; } test=test.next; n--; } ListNode pre = dummynode; ListNode cur = head; while(test!=null){ pre=cur; cur=cur.next; test=test.next; } head=cur; pre.next=null; while(cur!=null){ pre=cur; cur=cur.next; } pre.next=dummynode.next; return head; }}
细节
0 0
- LeetCode 061 Rotate List
- 061 Rotate List [Leetcode]
- LeetCode 061 Rotate List
- leetcode 061 Rotate List
- Leetcode 061 Rotate List
- LeetCode 061 Rotate List
- 【LeetCode OJ 061】Rotate List
- [leetcode][list] Rotate List
- leetcode 061 —— Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- eclipse不能启动的解决方案
- CentOS硬盘安装方法
- 使用 FSharpx.TypeProviders.Excel 类型提供程序的方法
- pat 1003
- ubuntu使用记录(一)
- LeetCode 061 Rotate List
- 对给定日期计算星期几
- mysql 慢查询日志
- pat 1004
- 如何实现批处理的连续调用?<一星>
- 1045. Favorite Color Stripe (30)
- Linux下可以批注,高亮的PDF阅读器
- 【记录】查找关于S3C6410中的中的-march,-mcpu,-mtune以及-mfpu和-mfloat-abi
- UVA 10791 - Minimum Sum LCM