定义数据结构如下:
function listNode(val) {
this.value = val;
this.next = null;
}
实现两个有序链表的合并
方法1:通过递归的方式实现,通过比对节点的大小,进行节点的插入,具体实现如下:
function merge(l1, l2) {
if (l1 === null) {
return l2;
}
if (l2 === null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = merge(l1.next, l2);
return l1;
} else {
l2.next = merge(l1, l2.next);
return l2;
}
}
方法2:通过while循环,通过链表l1,l2的节点不为空进行判断,如果l1空,剩余的l2节点直接插入就可以了,如果l2空,剩余的l1节点直接插入就可以了,具体实现如下:
function merge(l1, l2) {
let res = {};
let current = res;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
current.next = l1.value;
current = current.next;
l1 = l1.next;
} else {
current.next = l2.value;
current = current.next;
l2 = l2.next;
}
}
if (l1 !== null) {
current.next = l1;
} else if (l2 !== null) {
current.next = l2;
}
return res.next;
}