题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
function ListNode(x){
this.val = x;
this.next = null;
}
function Merge(pHead1, pHead2)
{
// write code here
//创建新的空链表
let current = new ListNode();
//创建哑节点,放置新链表之前,占位(因为current要向前移动,不占位无法找回头指针返回完整链表)
let dummy = current;
//p1,p2不为空
while(pHead1 !== null && pHead2 !== null){
//判断大小
if(pHead1.val < pHead2.val){
//将小的节点存入新链表
current.next = pHead1;
//并移动p1指针
pHead1 = pHead1.next;
}else{
current.next = pHead2;
pHead2 = pHead2.next;
}
//存放完节点,移动新链表指针
current = current.next;
}
//当比较完,如果有链表有剩余节点
if(pHead1 !== null){
//因为是递增链表,没有比较完的所有节点一定都比新链表大,直接存放
current.next = pHead1;
}
if(pHead2 !== null){
current.next = pHead2;
}
//dummy在新链表之前,dummy.next才是完整链表
return dummy.next;
}
module.exports = {
Merge : Merge
};