25. K个一组翻转链表
遇到困难直接看题解 --_--,每k个一组,进行翻转,然后再装回原链表中。
class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode hair = new ListNode(0); //头结点 hair.next = head; ListNode pre = hair; while (head != null) { ListNode tail = pre; //长度小于k时直接返回 for (int i = 0 ; i < k; i++) { tail = tail.next; if (tail == null) return hair.next; } ListNode nex = tail.next; ListNode[] reverse = myReverse(head,tail); head = reverse[0]; tail = reverse[1]; //子链表装回原链表 pre.next = head; tail.next = nex; pre = tail; head = tail.next; } return hair.next; } public ListNode[] myReverse(ListNode head, ListNode tail) { ListNode prev = tail.next; ListNode p = head; while(prev != tail) { ListNode nex = p.next; p.next = prev; prev = p; p = nex; } return new ListNode[] {tail, head}; } }