2024/8/26 LeetCode Hot100 LinkedList
This commit is contained in:
parent
e488b9cad9
commit
f905bd9bca
|
@ -0,0 +1,54 @@
|
|||
package com.cool.hot100.linkedlist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/08/26/23:12
|
||||
* DayNumber 2
|
||||
* Hard 3
|
||||
*/
|
||||
public class Num23 {
|
||||
|
||||
|
||||
public ListNode mergeKLists(ListNode[] lists) {
|
||||
if (lists.length == 0) return null;
|
||||
List<ListNode> list = Arrays.stream(lists).collect(Collectors.toList());
|
||||
while (list.size() > 1) {
|
||||
for (int i = list.size() - 1; i > 0; i -= 2) {
|
||||
|
||||
ListNode listNode = list.get(i);
|
||||
ListNode listNode1 = list.get(i - 1);
|
||||
ListNode newListNode = merge(listNode1, listNode);
|
||||
list.remove(i);
|
||||
list.remove(i-1);
|
||||
list.add(newListNode);
|
||||
|
||||
}
|
||||
}
|
||||
return list.get(0);
|
||||
}
|
||||
|
||||
public ListNode merge(ListNode node1, ListNode node2) {
|
||||
ListNode head = new ListNode(0);
|
||||
ListNode node = head;
|
||||
while (node1 != null && node2 != null) {
|
||||
if (node1.val <= node2.val) {
|
||||
node.next = node1;
|
||||
node1 = node1.next;
|
||||
} else {
|
||||
node.next = node2;
|
||||
node2 = node2.next;
|
||||
}
|
||||
node = node.next;
|
||||
}
|
||||
node.next = node1 == null ? node2 : node1;
|
||||
return head.next;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue