Rotate List
来源:互联网 发布:微屏软件科技有限公司 编辑:程序博客网 时间:2024/05/15 01:57
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
.
思路:首先算length,然后k%length,然后fast slow, fast先走k步,然后一起走,最后找到newhead,然后连起来,注意k==0,return head;
/** * 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) return head; int len = 0; ListNode node = head; while(node!=null) { node = node.next; len++; } k = k%len; if(k == 0) return head; ListNode slow = head; ListNode fast = head; int step = k; while(step>0){ fast = fast.next; step--; } while(fast != null && fast.next!=null){ slow = slow.next; fast = fast.next; } ListNode newhead = slow.next; slow.next = null; fast.next = head; return newhead; } }
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- python kNN算法
- 惰性杀死理想
- 信号量中的PV操作
- Java 过滤Oracle的like条件的特殊字符
- UVA 10125 Sumsets
- Rotate List
- HDU-1129 Channel Allocation
- ACM HDOJ 1297 (Children’s Queue)
- I/O系统:中断、DMA、通道
- 编写函数 fun求出 x 的所有奇数因子
- word分栏及序号对齐
- 定义文档兼容性,让IE按照指定的浏览器版本解析页面
- JAVA JS 身份证正则表达式
- Same Tree