思路:
// @Title: K 个一组翻转链表 (Reverse Nodes in k-Group)
// @Author: qisiii
// @Date: 2024-04-13 23:24:17
// @Runtime: 0 ms
// @Memory: 43.4 MB
// @comment:
// @flag:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(k==1){
return head;
}
ListNode temp = head;
int size = 0;
while (temp != null) {
size++;
temp = temp.next;
}
if (size < k) {
return head;
}
int kB = k;
ListNode result = new ListNode(-1, head);
ListNode pre = result, cur = pre.next, next;
while (kB > 1) {
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next=next;
kB--;
}
cur.next = reverseKGroup(cur.next, k);
return result.next;
}
}