LeetCode Reverse Nodes in k-Group
2016-01-08 08:50
561 查看
Description:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
For k = 2, you should return:
For k = 3, you should return:
Solution:
一开始还在想有没有什么复杂的优化,最后发现单纯写出来就很好了。
我的写法是最naive的写法,似乎有更好的,等我刷完再慢慢更新哈~~~
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
1->2->3->4->5
For k = 2, you should return:
2->1->4->3->5
For k = 3, you should return:
3->2->1->4->5
Solution:
一开始还在想有没有什么复杂的优化,最后发现单纯写出来就很好了。
我的写法是最naive的写法,似乎有更好的,等我刷完再慢慢更新哈~~~
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (head == null) return head; int i = 0; ListNode neoHead = head; for (i = 1; i < k; i++) { if (neoHead.next == null) break; neoHead = neoHead.next; } if (i < k) return head; ListNode lastTail = null, currentHead, currentTail, nextHead; ListNode temp, pre, cur; while (true) { if (lastTail == null) currentHead = head; else currentHead = lastTail.next; currentTail = currentHead; for (i = 1; i < k; i++) { if (currentTail.next == null) break; currentTail = currentTail.next; } if (i < k) return neoHead; nextHead = currentTail.next; currentTail.next = null; if (lastTail == null) lastTail = currentHead; else { lastTail.next = currentTail; lastTail = currentHead; } temp = currentHead.next; pre = currentHead; cur = currentHead; while (temp != null) { cur = temp; temp = temp.next; cur.next = pre; pre = cur; } currentHead.next = nextHead; if (nextHead == null) break; } return neoHead; } }
相关文章推荐
- windows下node.js安装图文教程
- Node.js
- nodejs安装不了和npm安装不了的解决方法
- Nodejs·理解Buffer
- node运行报错: Error: listen EADDRINUSE :::3000 e
- node+express读书笔记1
- nodejs监控目录
- Node.js学习笔记(一)-认识Node.js
- node.js学习笔记之promise
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 25 - Reverse Nodes in k-Group
- hadoop2.2 datanode 启动不了
- nodejs 中Express 的 send方法
- apidoc 监视文件变动自动生成工具
- Leetcode217: Reverse Nodes in k-Group
- [leedcode oj 237]Delete Node in a Linked List
- Node.js入门和学习指导
- 【2-3】HDFS之DataNode
- LeetCode 24 - Swap Nodes in Pairs
- 【LeetCode】237. Delete Node in a Linked List(链表)