题目描述

  1. 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:

1
2
3
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

1
2
3
输入:l1 = [], l2 = []
输出:[]

示例 3:

1
2
3
输入:l1 = [], l2 = [0]
输出:[0]

解法

  • 简单迭代
  • 每次在个链表之间寻找最小的值,将其加入新的链表中,最后返回链表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode pre=new ListNode(-1);//用于存放先前的值
ListNode head=pre;//返回时的整个链表的头节点
while (list1!=null&&list2!=null){
//循环条件是都没有遍历完
if(list1.val<list2.val){
pre.next=list1;
list1=list1.next;
}
else {
pre.next=list2;
list2=list2.next;
}
pre=pre.next;
}
//任意一表遍历完后直接另一个链表的剩余部分加入到新建的链表中
if(list1==null){
pre.next=list2;
}
else {
pre.next=list1;
}
return head.next;
}
}
  • 时间复杂度:O(m+n)

来源:力扣(LeetCode)
链接:21. 合并两个有序链表 - 力扣(LeetCode) (leetcode-cn.com)