21-合并两个有序链表

21-合并两个有序链表

力扣21

https://leetcode-cn.com/problems/merge-two-sorted-lists/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//虚拟头部
ListNode root = new ListNode(), cur = root;
//先合并公共长度部分
while (l1 != null && l2 != null){
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
}else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
//剩下的直接接上
cur.next = (l1 == null) ? l2 : l1;
return root.next;
}

其他链表类型的题目点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×