# 力扣25_K个一组翻转链表

k 是一个正整数，它的值小于或等于链表的长度。

public ListNode reverseKGroup(ListNode head, int k) {

ListNode newHead = reverseList(a, b);

//递归反转以b开头，k为一组的链表
ListNode nextNode = reverseKGroup(b, k);

//组与组之间连接
a.next = nextNode;



public ListNode reverseList(ListNode a, ListNode b) {
ListNode prev = null;
ListNode cur = a;
while(cur != null && cur != b){
ListNode nextTemp = cur.next;
cur.next = prev;
prev = cur;
cur = nextTemp;
}
return prev;
}


class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null) return null;
ListNode a = head;
ListNode b = head;
//找到下一个待反转的位置 发现子问题和原问题完全相同
for(int i = 0; i < k; i++){
if(b == null){
}
b = b.next;
}

ListNode newHead = reverseList(a, b); //k个节点反转
ListNode nextHead = reverseKGroup(b, k); //递归

}

//反转区间[a,b)的链表
public ListNode reverseList(ListNode a, ListNode b) {
ListNode prev = null;
ListNode cur = a;
while(cur != null && cur != b){
ListNode nextTemp = cur.next;
cur.next = prev;
prev = cur;
cur = nextTemp;
}
return prev;
}
}


class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);

ListNode pre = dummy;
ListNode end = pre;

while(end.next!=null) {

for(int i = 0; i < k && end!=null; ++i) end = end.next;
if(end == null) break;
ListNode start = pre.next;
ListNode nextNode = end.next;
end.next = null;
pre.next = reverseList(start);
start.next = nextNode;
pre = start;

end = pre;
}
return dummy.next;

}

//反转链表
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode nextNode = cur.next;
cur.next = pre;
pre = cur;
cur = nextNode;
}
return pre;
}
}


05-25 213

04-27 135
09-23 110
06-03 1117
06-24 463
05-16 88
01-29 88
04-18 186
04-17 626
©️2020 CSDN 皮肤主题: 1024 设计师:白松林