链表分组反转 - 技术面手撕代码(Java)-LMLPHP


import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

class Solution {

    public ListNode reverseKGroup(ListNode head, int k) {
        Deque<ListNode> deque = new LinkedList<>();
        ListNode cur = head;
        while (cur != null) {
            deque.offerLast(cur);
            cur = cur.next;
        }

        //  进行分组
        List<List<ListNode>> groups = new ArrayList<>();
        while (!deque.isEmpty()) {
            List<ListNode> temp = new ArrayList<>();
            for (int i = 0; i < k && !deque.isEmpty(); i++) {
                temp.add(deque.pollLast());
            }

            groups.add(temp);
        }

        ListNode result = new ListNode(-1);
        ListNode tail = result;
        for (int i = groups.size() - 1; i >= 0; i--) {
            List<ListNode> temp = groups.get(i);
            if (temp.size() == k) { // 翻转
                for (ListNode t : temp) {
                    tail = tail.next = t;
                }
            } else { // 不翻转
                for (int j = temp.size() - 1; j >= 0; j--) {
                    tail = tail.next = temp.get(j);
                }
            }
        }
        tail.next = null;

        return result.next;
    }


    public static void main(String[] args) {
        List<ListNode> list = new ArrayList<>();
        for (int i = 1; i <= 8; i++) {
            list.add(new ListNode(i));
        }

        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).next = list.get(i + 1);
        }

        Solution solution = new Solution();
        ListNode rs = solution.reverseKGroup(list.get(0), 3);
        while (rs != null) {
            System.out.println(rs.val);
            rs = rs.next;
        }
    }

}

03-14 17:10