合并两个升序链表
题目
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的
链接
思路
用两个指针指向两条链表头,先获取两者中更小的作为新链表的头结点,然后两个指针在两个链表上滑动,每次比较两个指针指的结点的值,将值更小的结点挂在新链表后面;当一方链表走完时直接将另一个指针对应的结点挂在新链表尾部
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return l1 == null ? l2 : l1;
}
ListNode head = l1.val <= l2.val ? l1 : l2;
ListNode cur1 = head.next;
ListNode cur2 = head == l1 ? l2 : l1;
ListNode pre = head;
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {
pre.next = cur1;
cur1 = cur1.next;
} else {
pre.next = cur2;
cur2 = cur2.next;
}
pre = pre.next;
}
pre.next = cur1 == null ? cur2 : cur1;
return head;
}
}
合并K个升序链表
题目
输入一个集合,集合中是k个升序链表,合并这k个升序链表
链表
思路
将合并k个链表转化为两两合并链表,用归并的思想提高合并的效率
class solution {
public ListNode mergeKLists(ListNode[] lists) {
return merge(lists, 0, lists.length - 1);
}
public ListNode merge(ListNode[] lists, int l, int r) {
if (l == r) {
return lists[l];
}
if (l > r) {
return null;
}
int mid = (l + r) >> 1;
return mergeTwo(merge(lists, l, mid), merge(lists, mid + 1, r));
}
public ListNode mergeTwo(ListNode node1, ListNode node2) {
if (node1 == null || node2 == null) {
return node1 == null? node2 : node1;
}
ListNode head = node1.val <= node2.val ? node1 : node2;
ListNode cur1 = head.next;
ListNode cur2 = head == node1 ? node2 : node1;
ListNode pre = head;
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {
pre.next = cur1;
cur1 = cur1.next;
} else {
pre.next = cur2;
cur2 = cur2.next;
}
pre = pre.next;
}
pre.next = cur1 != null ? cur1 : cur2;
return head;
}
}