1、合并两个有序链表
Leetcode 21;easy;
递归和迭代两个版本需要掌握。
package linkedlist;
public class Main0021合并两个有序链表 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(4);
ListNode l2 = new ListNode(2);
ListNode node3 = new ListNode(5);
l1.next = node1;
node1.next = node2;
l2.next = node3;
ListNode node = new Solution21().mergeTwoLists(l1, l2);
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
}
// 递归
class Solution21 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
// 迭代
class Solution021 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l2 = l2.next;
} else {
cur.next = l2;
l1 = l1.next;
}
cur = cur.next;
}
cur.next = l1 == null ? l2 : l1;
return dummy.next;
}
}
2.合并K个排序链表
Leetcode 23;hard;
合并K个排序链表采用了归并排序思想、合并两条链表结合即可!
package linkedlist;
class Solution23 {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0)
return null;
return merge(lists, 0, lists.length - 1);
}
// 1,2,3,4 分别代表一条链表 l1返回1、2的合并链表,l2返回3、4的合并链表
// 最后返回1,2,3,4的合并链表
// 归并思想
public ListNode merge(ListNode[] lists, int left, int right) {
if (left == right)
return lists[left];
int mid = (left + right) / 2;
ListNode l1 = merge(lists, left, mid);
ListNode l2 = merge(lists, mid + 1, right);
return mergeTwoList(l1, l2);
}
public ListNode mergeTwoList(ListNode l1, ListNode l2) {//合并两条链表
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoList(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoList(l1, l2.next);
return l2;
}
}
}