题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null || head.next == null || k == 1) return head;
ListNode front = new ListNode(-1);
ListNode cur = head;
front.next = head;
ListNode l = null;
ListNode prel = front;
ListNode next = null;
boolean reverse = false;
while (head != null) {
int q = k;
while (head != null && q-- > 0) {
head = head.next;
}
if (q == -1 || q == 0) {
reverse = true;
ListNode pre = cur;
l = pre;
cur = cur.next;
for (int i = 1; i < k; i++) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
prel.next = pre;
prel = l;
}
if (q >= 0) {
if (reverse)
l.next = next;
}
}
return front.next;
}
}