LinkedList----- List 61. Rotate List
来源:互联网 发布:阿里云终端管理工具 编辑:程序博客网 时间:2024/06/05 06:46
题目连接
这道题通过率略低,,不知道为什么,有好几种的做法,几乎没什么难度,不过要是能在O(1)空间内就行了。
public ListNode rotateRight(ListNode head, int k) { if (head == null) { return head; } ListNode p = head; int len = computeLength(p); int step = k % len; if (step == 0) { return head; } int pre = len - step; p = head; ListNode q = combinateList(p); ListNode result = help(q, pre, len); return result; } public int computeLength(ListNode head) { ListNode p = head; int counter = 0; while (p != null) { counter++; p = p.next; } return counter; } public ListNode combinateList(ListNode head) { ListNode p = head; ListNode list1 = head; ListNode list2 = null; ListNode q = null; while (p.next != null) { ListNode node = new ListNode(p.val); if (list2 == null) { list2 = node; q = list2; } else { q.next = node; q = q.next; } p = p.next; } q.next = new ListNode(p.val); q.next.next = null; p.next = list2; System.out.println("合并后:"); printListNode(list1); return list1; } public ListNode help(ListNode head, int pre, int len) { ListNode q = head; ListNode result = null; ListNode p = null; int counter = 0; int inCounter = 0; while (q != null) { q = q.next; if (result == null) { counter++; if (counter == pre) { result = new ListNode(q.val); p = result; inCounter++; } } else { inCounter++; p.next = new ListNode(q.val); p = p.next; if (inCounter == len) { q = null; p = null; } } } return result; } public void printListNode(ListNode head) { ListNode p = head; while (p != null) { System.out.print(p.val + "->"); p = p.next; } System.out.print("NULL"); }
阅读全文
0 0
- LinkedList----- List 61. Rotate List
- 61. Rotate List leetcode list
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- Linux系统的firewalld服务
- [NOIP模拟赛]TPS
- POJ-2406 Power Strings(KMP求重复子串出现的最大次数)
- 【单片机笔记】51内核软件延时和串口的巧妙使用方法
- sdk、jdk、jre的区别
- LinkedList----- List 61. Rotate List
- unity 3D:自动寻路
- JAVAEE之Spring学习(一)-----ioc容器
- 按位与&或|运算实现组合属性
- 反思总结1
- 关于驱动的probe(引用)
- 野蛮生长后,网络自制剧如何摆脱诸多顽疾?
- 只包含因子2 3 5的数
- Core Erlang:Erlang的Core中间表示