题解 | #链表中的节点每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 ListNode dummy = new ListNode(-1); dummy.next = head; for(ListNode p = dummy;;){ ListNode q = p; // 看看当前有没有k个 for(int i = 0; i < k && q != null; i ++) q = q.next; if(q == null) break; ListNode a = p.next, b = a.next; for(int i = 0; i < k - 1; i ++){ ListNode c = b.next; b.next = a; a = b; b = c; } ListNode c = p.next; p.next = a; c.next = b; p = c; } return dummy.next; } }