leetcode 21.合并两个有序链表
解题思路:
创建一个新的链表,然后双指针循环两个有序链表,值小的先合并,值相等都合并,然后再判断如果两个链表有没遍历完的,就直接合并到新链表,最后返回值
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
function mergeTwoLists (l1, l2) {
//1.创建头节点
var head = new ListNode(0)
var current = head;
//2.双指针循环遍历
while(l1 && l2) {
//2.1 值小的合并到新链表
if(l1.val < l2.val) {
current.next = new ListNode(l1.val);
current = current.next
l1 = l1.next
}else if (l1.val == l2.val) { //2.2 值相等都并入
current.next = new ListNode(l1.val);
current = current.next;
l1 = l1.next
current.next = new ListNode(l2.val);;
current = current.next;
l2 = l2.next;
}else {
current.next = new ListNode(l2.val);;
current = current.next;
l2 = l2.next;
}
// console.log(new ListNode())
}
//3.检查,没用遍历完的直接并入新链表
if(l1 != null){
current.next = l1
}
if(l2 != null){
current.next = l2
}
//4.返回head.next
return head.next
}
var l1 = {
val: 1,
next: {
val: 2,
next: {
val: 4,
next: null
}
}
}
var l2 = {
val: 1,
next: {
val: 3,
next: {
val: 5,
next: {
val: 6,
next: null
}
}
}
}
console.log(mergeTwoLists(l1, l2));
打印结果如下:
牛客网:
function Merge(pHead1, pHead2)
{
// write code here
if(pHead1 == null) {
return pHead2
}
if(pHead2 == null){
return pHead1
}
//定义一个新的head用来合并链表
let head = new NodeList(0)
let current = head
while(pHead1 && pHead2){
//值小就先合并
if(pHead1.val < pHead2.val) {
current.next = pHead1
current = current.next
pHead1 = pHead1.next
}else if(pHead1.val == pHead2.val) { //值相等就都合并
current.next = pHead1
current = current.next
pHead1 = pHead1.next
current.next = pHead2
current = current.next
pHead2 = pHead2.next
}else {
current.next = pHead2
current = current.next
pHead2 = pHead2.next
}
}
//检查,没有合并完的直接并入
if(pHead1 !==null){
current.next = pHead1
}
if(pHead2 !==null){
current.next = pHead2
}
return head.next
}
不积跬步无以至千里