(链表)05-合并K个已排序的链表

 1 import java.util.*;
 2 
 3 /**
 4  * Definition for singly-linked list.
 5  * public class ListNode {
 6  *     int val;
 7  *     ListNode next;
 8  *     ListNode(int x) {
 9  *         val = x;
10  *         next = null;
11  *     }
12  * }
13  */
14 public class Solution {
15 
16     public ListNode mergeKLists(ArrayList<ListNode> lists) {
17         // 初始返回结果
18         ListNode result = null;
19         // 依次将待合并的链表与当前返回结果进行合并
20         for(ListNode node : lists) {
21             result = merge(result, node);
22         }
23         // 返回结果
24         return result;
25     }
26 
27     public ListNode merge(ListNode list1,ListNode list2) {
28         // 添加头节点
29         ListNode root = new ListNode(-1);
30         // 定义临时变量
31         ListNode temp1 = list1;
32         ListNode temp2 = list2;
33         ListNode current = root;
34         // 拼接新链表
35         while(temp1 != null && temp2 != null) {
36             if (temp1.val < temp2.val) {
37                 current.next = temp1;
38                 temp1 = temp1.next;
39             } else {
40                 current.next = temp2;
41                 temp2 = temp2.next;
42             }
43             current = current.next;
44         }
45         if (temp1 == null) {
46             current.next = temp2;
47         }
48         if (temp2 == null) {
49             current.next = temp1;
50         }
51         // 返回结果
52         return root.next;
53     }
54 }
 1 import java.util.*;
 2 
 3 /**
 4  * Definition for singly-linked list.
 5  * public class ListNode {
 6  *     int val;
 7  *     ListNode next;
 8  *     ListNode(int x) {
 9  *         val = x;
10  *         next = null;
11  *     }
12  * }
13  */
14 public class Solution {
15 
16     public ListNode mergeKLists(ArrayList<ListNode> lists) {
17         // 验证特殊场景
18         if(lists == null || lists.size() == 0) {
19             return null;
20         }
21         // 使用递归排序的思想合并链表
22         return mergeGroupLists(lists, 0, lists.size() - 1);
23     }
24 
25     public ListNode mergeGroupLists(List<ListNode> lists, int left, int right) {
26         // 返回区间合并结果
27         if (left == right) {
28             return lists.get(left);
29         }
30         // 计算中间点
31         int mid = (left + right) / 2;
32         // 将两个链表合并成一个链表
33         return merge(mergeGroupLists(lists, left, mid), mergeGroupLists(lists, mid + 1, right));
34     }
35 }

 

posted @ 2023-11-14 23:33  StringBuilder  阅读(14)  评论(0)    收藏  举报