[Leetcode] Reverse Nodes in k-Group
2015-12-03 19:50
519 查看
Problem:
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:
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
/** * 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 <= 0) { throw new IllegalArgumentException("k <= 0"); } if(k == 1) { return head; } ListNode dummy1 = new ListNode(0); // head node of the original list ListNode dummy2 = new ListNode(0), tail2 = null; // head node of the working list for reversing ListNode dummy3 = new ListNode(0), tail3 = dummy3; // head node of resulting list dummy1.next = head; dummy2.next = null; dummy3.next = null; int i = 1; // the nth node in the original list while(dummy1.next != null) { // Remove from the original list ListNode curr = dummy1.next; dummy1.next = curr.next; // Add to the head of reversed list curr.next = dummy2.next; dummy2.next = curr; if(i % k == 0) { // a group of k nodes has been reversed tail3.next = dummy2.next; dummy2.next = null; tail3 = tail2; }else if(i % k == 1) { tail2 = curr; tail2.next = null; } i++; } while(dummy2.next != null) { ListNode p = dummy2.next; dummy2.next = p.next; p.next = tail3.next; tail3.next = p; } return dummy3.next; } }
相关文章推荐
- nodejs杂谈二:jshint
- monodevelop 突然莫名其妙的将 warning 全部标记为 error
- Remove Nth Node From End of List 从链表中删除倒数第N的节点
- Node.js 安装配置
- nodejs+express+jade创建新文件
- nodejs笔记杂谈
- Node.js 学习一(Node.js 安装)
- 开发日记——LastWord
- nodejs事件循环
- Node.js REPL(交互式解释器) Node.js 回调函数
- Zookeeper管理工具node-zk-browser
- How do I get started with Node.js
- Node.js 环境配置记录
- Notepad++ 配置 Node.js 开发环境
- node.js
- [Leetcode] Swap Nodes in Pairs
- Node.js + Express + Ubuntu
- Leetcode177: Count Complete Tree Nodes
- node js 调试
- nodeJs+jquery实现聊天插入表情功能