面试记录

75 阅读1分钟

1、js链表反转

function reverseNode(head) {
  let c = head;
  let q = null;
  let list = head
  while (c.next) {
    q = c.next
    c.next = q.next
    q.next = list
    list = q
  }
  return list
}

2、快慢指针删除倒数第n个

function quickslowNode(head, n) {
    var dummy = new Object();
    dummy.next = head;
    var q = dummy;
    var s = dummy;
    // q先走n部
    while (n > 0) {
        q = q.next;
        n--;
    }
    // s和q一起走
    while (q.next) {
        q = q.next;
        s = s.next;
    }
    // 删除n位置的值
    s.next = s.next.next;
    return dummy.next;
}

3、将两个有序链表合并成一个无序链表

function mergeTwoList(l1: Provider, l2: Provider) {
  let head: Provider = new Object()
  let cur = head
  while (l1 && l2 && l1.val && l2.val) {
    if (l1!.val <= l2!.val) {
      cur.next = l1
      l1 = l1.next
    } else {
      cur.next = l2
      l2 = l2.next
    }
    cur = cur.next
  }
  // 处理不等长
  cur.next = l1 ? l1 : l2
  return head.next
}