21.合并两个有序链表
小于 1 分钟
21.合并两个有序链表
/*
* @lc app=leetcode.cn id=21 lang=typescript
*
* [21] 合并两个有序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
function mergeTwoLists(
list1: ListNode | null,
list2: ListNode | null
): ListNode | null {
if (!list1) return list2;
if (!list2) return list1;
if (list1.val < list2.val) {
const rst = mergeTwoLists(list1.next, list2);
list1.next = rst;
return list1;
} else {
const rst = mergeTwoLists(list1, list2.next);
list2.next = rst;
return list2;
}
}
// @lc code=end
Loading...
