题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode res; public ListNode reverseKGroup (ListNode head, int k) { if(k < 2 || head == null || head.next == null) return head; // write code here recursion(head, k, null); return res; } public void recursion(ListNode head, int k, ListNode thePre) { if(head == null) return; ListNode p = head, q = head; int count = 1; while(q != null && count != k) { q = q.next; if(q != null) count++; } if(count != k) { if(thePre == null) { res = head; } return; } if(thePre != null) thePre.next = null; ListNode other = q.next; q.next = null; ListNode pre = null; ListNode cur = p; ListNode next = cur.next; while(cur != null) { cur.next = pre; pre = cur; cur = next; next = next==null?null:next.next; } p.next = other; if(thePre != null) { thePre.next = q; }else { res = q; } recursion(other, k, p); } }递归解法,与君共赏