2.2.9 Reverse Nodes in K-group
来源:互联网 发布:上海软件测试培训 编辑:程序博客网 时间:2024/05/28 15:07
Link: https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
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
我的思路:1 递归。同上一题。我的代码是:
但写不出来。再做。
public class Solution { //recursive public ListNode reverseKGroup(ListNode head, int k) { ListNode p = head; for(int i = 0; i < k-1; i++){ if(p == null) return null; p = p.next; } head.next = reverseKGroups(p.next, k); //crease reverse links of k nodes reverse (head, k); return p; } public void createReverseLinks(ListNode head, int k){ }}
Approach II: Iterative
对每个节点,找出k-node group的时候要遍历一次。reverse这个k-node group要再遍历一次。所以对每个节点,遍历两次。所以Time = O(n)
Time: O(n), Space: O(1)
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode preStart = dummy; while(preStart != null){ ListNode start = preStart.next; ListNode end = preStart;//the end node of the k-node group for(int i = 0; i < k; i++){ end = end.next; if(end == null) return dummy.next; } preStart.next = reverse(start, end);//connect preStart with the head of the reversed group //let preStart jump k nodes to reach the previous node of the next k-node group for(int i = 0; i < k; i++){ preStart = preStart.next; } } return dummy.next; } public ListNode reverse(ListNode start, ListNode end){ ListNode pre = start; ListNode cur = start.next; ListNode afterEnd = end.next; while(cur != afterEnd){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } start.next = afterEnd; return end; }}Note:
end 必须要初始化成preStart
for 循环里面的两句先后顺序不能反。
否则会出现错误:
ListNode end = preStart;//the end node of the k-node group for(int i = 0; i < k; i++){ end = end.next; if(end == null) return dummy.next; }
0 0
- 2.2.9 Reverse Nodes in k-Group
- 2.2.9 Reverse Nodes in K-group
- 2.2.9—单链表—Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- CentOS中vsftp安装与配置
- ftp vsftpd详细配置
- PhoneGap移动开发框架
- 基于REST的Web服务
- Web Service程序开发
- 2.2.9 Reverse Nodes in K-group
- 自定义数据库厨师这和进步着
- vsftpd配置文件详解
- OpenGL教程
- 黑马程序员 异常
- 今日作息及食谱(8.25)
- iOS应用开发视频教程笔记(九)Table Views
- 【iOS界面处理】使用storyboard实现页面跳转,简单的数据传递
- How To: Configure Secure FTP Server (VSFTPD)