技术求助:如何对单链表按k个节点分组进行排序?
Solution for Grouped LinkedList Sorting by k Nodes
Hey there! Since you already have a working sortedMerge function for full linked list merge sort, we can adapt that logic to solve the grouped sorting problem. Here's a step-by-step breakdown and implementation:
Key Steps to Solve This
- Split the original list into chunks: Each chunk has up to
knodes. We need to handle the last chunk which might have fewer thanknodes. - Sort each individual chunk: Use your existing merge sort logic (or even insertion sort, which is efficient for small
k) on each chunk. - Reconnect all sorted chunks: Link the end of one sorted chunk to the start of the next sorted chunk to form the final list.
Implementation Code
First, let's add helper functions to split the list and handle the grouping, then integrate your existing sortedMerge for sorting chunks.
class LinkedListNode { int val; LinkedListNode next; LinkedListNode(int val) { this.val = val; } } // Your existing sortedMerge function (completed) LinkedListNode sortedMerge(LinkedListNode a, LinkedListNode b) { LinkedListNode result = null; if (a == null) return b; if (b == null) return a; if (a.val <= b.val) { result = a; result.next = sortedMerge(a.next, b); } else { result = b; result.next = sortedMerge(a, b.next); } return result; } // Helper to perform merge sort on a single linked list chunk LinkedListNode mergeSort(LinkedListNode head) { if (head == null || head.next == null) return head; // Split into two halves LinkedListNode mid = getMiddle(head); LinkedListNode nextOfMid = mid.next; mid.next = null; // Recursively sort both halves LinkedListNode left = mergeSort(head); LinkedListNode right = mergeSort(nextOfMid); // Merge the sorted halves return sortedMerge(left, right); } // Helper to find the middle node of a linked list LinkedListNode getMiddle(LinkedListNode head) { if (head == null) return head; LinkedListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } // Helper to split the list into k-length chunks, sort each, and reconnect LinkedListNode sortKGroupedLinkedList(LinkedListNode head, int k) { if (head == null || k <= 1) return head; LinkedListNode dummy = new LinkedListNode(0); dummy.next = head; LinkedListNode prevChunkTail = dummy; LinkedListNode current = head; while (current != null) { // Step 1: Find the end of the current k-length chunk LinkedListNode chunkHead = current; int count = 1; while (current.next != null && count < k) { current = current.next; count++; } // Save the start of the next chunk LinkedListNode nextChunkHead = current.next; // Cut off the current chunk from the rest of the list current.next = null; // Step 2: Sort the current chunk LinkedListNode sortedChunk = mergeSort(chunkHead); // Step 3: Link the sorted chunk to the previous part prevChunkTail.next = sortedChunk; // Move prevChunkTail to the end of the sorted chunk while (prevChunkTail.next != null) { prevChunkTail = prevChunkTail.next; } // Move to the next chunk current = nextChunkHead; } return dummy.next; } // Test the implementation public static void main(String[] args) { // Build the example list: 4->8->3->1->9->2 LinkedListNode head = new LinkedListNode(4); head.next = new LinkedListNode(8); head.next.next = new LinkedListNode(3); head.next.next.next = new LinkedListNode(1); head.next.next.next.next = new LinkedListNode(9); head.next.next.next.next.next = new LinkedListNode(2); int k = 3; LinkedListNode result = sortKGroupedLinkedList(head, k); // Print the result: 3->4->8->1->2->9 while (result != null) { System.out.print(result.val + "->"); result = result.next; } System.out.println("null"); }
Explanation of Key Parts
- Chunk Splitting: The loop in
sortKGroupedLinkedListiterates through the list, marking the start and end of each k-length chunk. We cut off the chunk from the rest of the list to sort it independently. - Chunk Sorting: We reuse your merge sort logic (via
mergeSortwhich calls yoursortedMerge) to sort each chunk. Ifkis small, you could also use insertion sort here for slightly better performance, but merge sort works perfectly too. - Reconnecting Chunks: After sorting a chunk, we link it to the end of the previously processed sorted chunks, then move the tail pointer forward to the end of the new sorted chunk.
Edge Cases Handled
k = 1: The function returns the original list since no sorting is needed.klarger than the list length: The entire list is sorted, just like your full merge sort.- Empty list: Returns null immediately.
内容的提问来源于stack exchange,提问作者roger_that
相关产品推荐
相关产品推荐

