合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
用JavaScript非递归和递归方式都AC了。
非递归:
function ListNode(x){
this.val = x;
this.next = null;
}
function Merge(pHead1, pHead2)
{
if(!pHead1) {
return !pHead2 ? null:pHead2;
}else if(!pHead2) {
return pHead1;
}
var ans = new ListNode(-1);
var l1 = pHead1;
var l2 = pHead2;
var cur = ans;
while (l1 && l2) {
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(!l1) {
cur.next = l2;
}
if(!l2) {
cur.next = l1;
}
return ans.next;
}
递归:
function ListNode(x){
this.val = x;
this.next = null;
}
function Merge(pHead1, pHead2)
{
if(pHead1 == null) {
return pHead2;
}
if(pHead2 == null) {
return pHead1;
}
var ans = null;
if(pHead1.val <= pHead2.val) {
ans = pHead1;
ans.next = Merge(pHead1.next,pHead2);
return ans;
}else {
ans = pHead2;
ans.next = Merge(pHead2.next,pHead1);
return ans;
}
return ans;
}
gtihub剑指offerAC代码仓库地址:传送
原文地址:https://www.cnblogs.com/zhangmingzhao/p/8439640.html
时间: 2024-10-12 22:18:33