题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例1
输入
{1,3,5},{2,4,6}
返回值
{1,2,3,4,5,6}
解法1:代码思路
比较两个链表(pHead1, pHead2)的首结点,哪个小的结点(假设pHead1较小)则合并到第三个链表(SortArray)尾结点,并(pHead1)向前移动一个结点。
结果会有一个链表先遍历结束,或者没有第三个链表尾结点指向剩余未遍历结束的链表
最后返回第三个链表首结点
解法1:代码
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2)
{
if (pHead1 === null) {
return pHead2;
}
if (pHead2 === null) {
return pHead1;
}
let SortArray=new ListNode(0);
let tempNode=SortArray;
while(pHead1!=null||pHead2!=null){
if(pHead1.val<pHead2.val){
tempNode.next=pHead1;
tempNode=tempNode.next;
pHead1=pHead1.next;
tempNode.next=null;
}
else{
tempNode.next=pHead2;
tempNode=tempNode.next;
pHead2=pHead2.next;
tempNode.next=null;
}
if(pHead1==null){
tempNode.next=pHead2;
break;
}
if(pHead2==null){
tempNode.next=pHead1;
break;
}
}
return SortArray.next;
}
运行环境:JavaScript (V8 6.0.0)
运行时间:10ms
占用内存:5324KB
解法2:代码思路
可用递归做,代码如下
解法2:代码
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2)
{
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;
}
}
运行环境:JavaScript (V8 6.0.0)
运行时间:9ms
占用内存:5332KB