File tree Expand file tree Collapse file tree 1 file changed +86
-0
lines changed
Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * int val;
5+ * ListNode next;
6+ * ListNode() {}
7+ * ListNode(int val) { this.val = val; }
8+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+ * }
10+ */
11+ class Solution {
12+ public ListNode mergeKLists (ListNode [] lists ) {
13+ List <ListNode > list = new LinkedList <>();
14+ for (ListNode l : lists ) {
15+ list .add (l );
16+ }
17+ return divide (list );
18+
19+ }
20+ public ListNode divide (List <ListNode > list ) {
21+ //두개씩 나누기. 두개 안되면 그냥 리스트에 넣고 리턴
22+ int n = list .size ();
23+ ListNode sum1 ;
24+ ListNode sum2 ;
25+ if (list .size () <= 2 ) {
26+ return merge (list );
27+ }
28+
29+ int mid = n / 2 ;
30+ List <ListNode > upper = new LinkedList <>();
31+ List <ListNode > last = new LinkedList <>();
32+
33+
34+ for (int i = 0 ; i < mid ; i ++) {
35+ upper .add (list .get (i ));
36+
37+ }
38+ sum1 = divide (upper );
39+
40+
41+ for (int i = mid ; i < n ; i ++) {
42+ last .add (list .get (i ));
43+ }
44+ sum2 = divide (last );
45+
46+ List <ListNode > m = new LinkedList <>();
47+ m .add (sum1 );
48+ m .add (sum2 );
49+
50+
51+ return merge (m );
52+
53+
54+ }
55+ public ListNode merge (List <ListNode > list ) {
56+ //edge
57+ if (list .size ()==0 ) return null ;
58+ if (list .size () == 1 ) return list .get (0 );
59+
60+ ListNode n1 = list .get (0 );
61+ ListNode n2 = list .get (1 );
62+ // System.out.println(n1.val + " : " + n2.val);
63+
64+ ListNode res = new ListNode (0 );
65+ ListNode head = res ;
66+
67+ while (n1 != null && n2 != null ) {
68+ if (n1 .val < n2 .val ){
69+ res .next = n1 ;
70+ res = res .next ;
71+ n1 = n1 .next ;
72+ } else {
73+ res .next = n2 ;
74+ res = res .next ;
75+ n2 = n2 .next ;
76+ }
77+
78+ }
79+ if (n1 == null ) res .next = n2 ;
80+ if (n2 == null ) res .next = n1 ;
81+ return head .next ;
82+
83+
84+
85+ }
86+ }
You can’t perform that action at this time.
0 commit comments