## 25. Reverse Nodes in k-Group 原

datacube

``````/**
*
* 1 转化为两两合并
*/
public class ReverseKGroup {

public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(4);
ListNode n3 = new ListNode(5);

l1.next = n1;
n1.next = n2;
n2.next = n3;

ReverseKGroup mt = new ReverseKGroup();
ListNode head = mt.reverseKGroup(l1,2);
}

public ListNode reverseKGroup(ListNode head, int k) {
if (k == 1 || head == null || head.next == null)
ListNode preHead = new ListNode(-1);
ListNode first = head, last = head;
ListNode preGroup = preHead, nextGroup = preHead;
int count = 1;
while (last != null) {
if (count == k) {          //当满足k个组合时进行翻转
nextGroup = last.next; //下一个组合的首节点
reverseList(first, last);
preGroup.next = last;  //翻转之后last已经是首节点
preGroup = first;      //preGroup设置自己为最末,此后first继续下一个组合,采用preGroup的深意,是不打扰first继续下一个组合

first.next = nextGroup;
first = nextGroup;
last = nextGroup;
count = 1;
continue;
}
last = last.next;
count++;
}
}

private void reverseList(ListNode head, ListNode tail) {
ListNode pre = new ListNode(-1), node = head;
while (pre != tail) {
ListNode temp = node.next;
node.next = pre;
pre = node;
node = temp;
}
}

}
``````

### datacube

Leetcode 25. Reverse Nodes in k-Group

SnailTyan
2018/09/28
0
0
leetcode 25: 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 sh......

2015/02/02
726
0
LeetCode：Reverse Nodes in k-Group - 分组翻转链表

1、题目名称 Reverse Nodes in k-Group（分组翻转链表） 2、题目地址 https://leetcode.com/problems/reverse-nodes-in-k-group 3、题目内容 英文： Given a linked list, reverse the nodes......

2015/08/10
247
0
Reverse Nodes in k-Group

[LeetCode] 025. Reverse Nodes in k-Group (Hard) (C++/Java)，有需要的朋友可以参考下。 索引：[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/l......

panpan123_
2017/01/16
0
0

237. Delete Node in a Linked List 这题跟正常的书里的删链表某个节点区别是传入的参数，书里函数输入是要删的那个节点的前一个节点，这题里给的函数输入就是要删的那个节点。 /** Definiti...

wcybrain
2017/10/31
0
0

Ø 能否有多个handler handler的构造方法 public Handler() { …. mLooper = Looper.myLooper(); mQueue = mLooper.mQueue; mCallback = null; … } 因为几乎主要的成员变量都是从Looper中拿......

shzwork
35分钟前
3
0

55分钟前
4
0
vue 源码 断点调试

4
0

TopkURLMapper public class TopkURLMapper extends Mapper<LongWritable, Text, Text, FlowBean> {private FlowBean bean = new FlowBean();private Text k = new Text();@Ove......

Garphy

4
0
OSChina 周六乱弹 —— 如果是个帅小伙你愿意和他出去吗

Osc乱弹歌单（2019）请戳（这里） 【今日歌曲】 小小编辑推荐：《Ghost 》游戏《死亡搁浅》原声 《Ghost 》游戏（《死亡搁浅》原声） - Au/Ra / Alan Walker 手机党少年们想听歌，请使劲儿戳...

441
15