Android大法好！！

# leetCode 25.Reverse Nodes in k-Group (以k个节点为一组反转链表) 解题思路和方法

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

    public ListNode reverseKGroup(ListNode head, int k) {
if(k < 2 || head == null){
return head;
}

int num = 1;//计数
ListNode pre = new ListNode(0);//定义头结点
pre.next = head;
ListNode firstNode = pre;//保存头结点
ListNode next = null;//下一个节点
ListNode cur = head.next;//当前节点
ListNode curHead = head;//不随位置改变的头结点（如1,2,3），curHead =1；变为321后，curHead仍=1
while(cur != null){//当前节点不为null
next = cur.next;//保存next节点
//交换节点
pre.next = cur;
cur.next = head;
curHead.next = next;//节点交换完成
//如果next==null,num+1与k比较后返回
if(next == null){
if(++num == k){
num = 1;
}
break;
}
//为下一循环准备
head = cur;
cur = next;
//如果已交换的节点==k,则pre等节点改变位置
if(++num == k){
num = 1;
pre = curHead;
curHead = cur;
head = cur;
cur = cur.next;
}
}
//如果num>1表明最后不够k的节点也交换了，交换回来即可
if(num > 1){
curHead = head = pre.next;
cur = head.next;
while(cur != null){//与上述代码类似
next = cur.next;
//交换数据
pre.next = cur;
cur.next = head;
curHead.next = next;
//更新数据，准备下一循环
head = cur;
cur = next;
}
}
return firstNode.next;
}

/**
* 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 < 2 || head == null){
return head;
}
int num = k;
ListNode p = head;
//判断节点个数与k的大小
while(num > 1 && p != null){
p = p.next;
num--;
}
if(p == null){//说明k比节点的个数大，直接返回
return head;
}
num = k;//再次赋初始值
p = head;
ListNode q = null;//定义两个临时周转节点
ListNode r = null;
while(num > 1){
q = p.next;//保存变量
r = q.next;
//交换节点
q.next = head;
p.next = r;
//变量前进
head = q;
num--;
}
p.next = reverseKGroup(p.next,k);//递归调用
return head;
}
}

#### 25. k个一组翻转链表

2018-04-17 11:12:54

#### 025 K个一组翻转链表

2018-04-17 15:47:37

#### 链表翻转（按K个一组）

2017-07-25 13:03:43

#### LetCode 25. k个一组翻转链表

2018-06-29 11:29:42

#### python--lintcode450. K组翻转链表

2018-06-11 17:18:24

#### leetcode--25. 每k个一组翻转链表

2018-04-10 15:13:06

#### 面试题—链表的‘部分’翻转

2016-08-09 21:43:37

#### PAT乙级练习题B1025.反转链表

2016-06-29 18:53:54

#### LeetCode：25. k个一组翻转链表

2018-06-04 20:31:33

#### 链表翻转（每K个结点进行一次逆置）

2017-07-24 13:01:01