JZ16 合并两个排序的链表

141 阅读1分钟

image.png


//递归版本

function ListNode(x){
    this.val = x;
    this.next = null;
}
function Merge(pHead1, pHead2)
{
    // write code here
   if(pHead1 == null)  return pHead2;
   if(pHead2 == null)  return pHead1
   if(pHead1.val <= pHead2.val){
      pHead1.next = Merge(pHead1.next, pHead2);
       return pHead1;
   else{
       pHead2.next = Merge(pHead1, pHead2.next);
       return pHead2;
   }   
}
module.exports = {
    Merge : Merge
};
//while 循环判断 拼接
function ListNode(x){
    this.val = x;
    this.next = null;
}
function Merge(pHead1, pHead2)
{
    // write code here
  let prehead=new ListNode(-1);
  let prev = prehead;
  while(pHead1&&pHead2) {
    if (pHead1.val>pHead2.val) {
      prev.next=pHead2
      pHead2=pHead2.next;
    }else {
      prev.next=pHead1
      pHead1=pHead1.next;
    }
    prev=prev.next;
  }
//把剩下的一项拼接上去
  prev.next =pHead1||pHead2;
 
  return prehead.next;
}
module.exports = {
    Merge : Merge
};