【leetCode 21】 合并两个有序链表

35 阅读1分钟

方法一:递归

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;
  }
}

const l3 = new ListNode(4);
const l2 = new ListNode(2, l3);
const l = new ListNode(1, l2);

const r3 = new ListNode(4);
const r2 = new ListNode(3, r3);
const r = new ListNode(1, r2);

//递归
function mergeTwoLists(
  list1: ListNode | null,
  list2: ListNode | null
): ListNode | null {
  // 都为空,则返回[]
  if (list1 == null && list2 == null) {
    return null;
  }

  //只有一个有数据,则返回有数据的链表
  if (list1 == null || list2 == null) {
    return list1 || list2;
  }

  if (list1.val < list2.val) {
    list1.next = mergeTwoLists(list1.next, list2);
    return list1;
  } else {
    list2.next = mergeTwoLists(list1, list2.next);
    return list2;
  }
}

方法二:迭代

//迭代
function mergeTwoLists(
  list1: ListNode | null,
  list2: ListNode | null
): ListNode | null {
  // 都为空,则返回[]
  if (list1 === null && list2 === null) {
    return null;
  }

  //只有一个有数据,则返回有数据的链表
  if (list1 === null || list2 === null) {
    return list1 || list2;
  }
  const ans = new ListNode(-1);
  let p = ans;
  while (list1 !== null && list2 !== null) {
    if (list1.val < list2.val) {
      p.next = list1;
      list1 = list1.next;
    } else {
      p.next = list2;
      list2 = list2.next;
    }
    p = p.next;
  }
  p.next = list1 === null ? list2 : list1;
  return ans.next;
}