LeetCode-206 A set of K inverted linked lists

Problem Description

Give you the head node of the linked list, flip every k nodes in a group, please return the modified linked list. k is a positive integer whose value is less than or equal to the length of the linked list. If the total number of nodes is not an integer multiple of k, then please keep the last remaining nodes in their original order. You can't just change the value inside the node, but you need to actually exchange the node.
Insert image description here

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

After reversing the linked list, the most intuitive solution to this problem is to split it into K sub-linked lists, reverse them, and then splice these sub-linked lists together in turn.
First, reverse the linked list

public static ListNode resverse(ListNode head){
    
    
        if (head == null) return null;
        ListNode cur = head;
        ListNode temp = null;
        ListNode dummy = new ListNode(0, null);
        while(cur!=null){
    
    
            temp = cur.next;
            cur.next = dummy.next;
            dummy.next = cur;
            cur = temp;
        }
        return dummy.next;
    }

Then reverse a group of K pieces in place, disconnect, reverse, and connect in three steps:
Insert image description here

public static ListNode reverseKGroup(ListNode head, int k) {
    
    
        ListNode dummy = new ListNode(0, head);
        ListNode end = dummy;
        ListNode pre = dummy;
        while (end!=null){
    
    
            ListNode start = pre.next;
            for (int i = 0; i < k && end != null; i++) {
    
    
                end = end.next; // end跑到待反转链表末端
            }
            if (end == null) break;
            ListNode next = end.next; // 提前保存好未反转链表的始端
            end.next = null; // 断开
            pre.next = resverse(start); // 反转,拼接
            // 下一轮反转节点赋值
            start.next = next; 
            pre = start;
            end = start;
        }
        return dummy.next;
    }

Guess you like

Origin blog.csdn.net/juggle_gap_horse/article/details/127887641
Recommended