pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

合并两个有序链表 #1006

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago
/*
 *  合并两个链表
 */
function Merge(head1, head2) {
  if (head1 == null)
    return head2;
  if (head2 == null)
    return head1;
  var cur1 = head1.next,       //遍历 head1 的指针 
     cur2 = head2.next,       //遍历 head2 的指针
    head = null,        //合并后链表的头结点
    cur = null;         //合并后的链表在尾结点
  //合并后链表的头结点为第一个结点元素最小的那个链表的头结点
  if (cur1.data > cur2.data) {
    head = head2;
    cur = cur2;
    cur2 = cur2.next;
  } else {
    head = head1;
    cur = cur1;
    cur1 = cur1.next;
  } 
  //每次找链表剩余结点的最小值对应的结点连接到合并后链表的尾部 
  while (cur1 && cur2) {
    if (cur1.data < cur2.data) {
      cur.next = cur1;
      cur = cur1;
      cur1 = cur1.next;
    } else {
      cur.next = cur2;
      cur = cur2;
      cur2 = cur2.next;
    }
  }
  //当遍历完一个链表后把另外一个链表剩余的结点链接到合并后的链表后面
  if (cur1 != null) {
    cur.next = cur1;
  }
  if (cur2 != null) {
    cur.next = cur2;
  }
  return head;
}