LeetCode : Reverse Nodes in k-Group [java]
2016-03-08 19:33
666 查看
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:
思路:分组逆转,注意组间连接。
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
思路:分组逆转,注意组间连接。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (k == 1 || head == null || head.next == null) return head; ListNode first = head, last = head; ListNode preHead = new ListNode(-1); preHead.next = head; ListNode preGroup = preHead, nextGroup = preHead; int count = 1; while (last != null) { if (count == k) { nextGroup = last.next; reverseList(first, last); preGroup.next = last; preGroup = first; first.next = nextGroup; first = nextGroup; last = nextGroup; count = 1; continue; } last = last.next; count++; } return preHead.next; } private void reverseList(ListNode head, ListNode tail) { ListNode pre = new ListNode(-1); ListNode node = head; pre.next = head; while (pre != tail) { ListNode temp = node.next; node.next = pre; pre = node; node = temp; } } }
相关文章推荐
- 第一天:NodeJs Windows环境搭建、学习资料地址、注意事项总结
- Node.js笔记之简介
- [node] ejs模板手册
- leetcode 25. Reverse Nodes in k-Group
- leetcode 24. Swap Nodes in Pairs
- [nodejs] cookie操作
- Wrtnode 配置方法:
- [LeetCode][JavaScript]Swap Nodes in Pairs
- [leetcode] 237. Delete Node in a Linked List
- Linode主机搭建(一)—— 注册账号和申请机器
- NodeJs初识模块开发
- 关于node引入到项目中的交流对话
- nodejs学习笔记四——express-session
- nodejs学习笔记三——nodejs使用富文本插件ueditor
- nodejs学习笔记一——nodejs安装
- 三种Node.js写文件的方式
- node下mysql入门
- LeetCode : Swap Nodes in Pairs [java]
- 三种Node.js写文件的方式
- Node.js笔记之模块机制