算法打卡第十二天

109 阅读1分钟
  1. 剑指 Offer 25. 合并两个排序的链表
  2. 剑指 Offer 52. 两个链表的第一个公共节点

剑指 Offer 25. 合并两个排序的链表

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

0 <= 链表长度 <= 1000

解题思路 暴力比较 定义两个变量,currentNode初始化头结点,newList=currentNode,一个用来迭代, 一个用来返回值 当l1和l2节点都存在是,开始比较此节点的值,如果l1的值小于等于l2则l1指向l1.next,currentNode.next指向此节点;否则l2指向l2.next 遍历完成后,如果l1还存在节点,则遍历l1, 将l1值的节点拷贝到next,currentNode 遍历完成后,如果l2还存在节点,则遍遍历l2, 将l1值的节点拷贝到next,currentNode 返回newList.next,因为初始化了一个为0的头结点

示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

var mergeTwoLists = function(l1, l2) {
    let currentNode = new ListNode(-1, null);
    let newList = currentNode;
    while (l1 && l2) {
        if (l1.val <= l2.val) {
            currentNode.next = new ListNode(l1.val, null);
            l1 = l1.next;
            currentNode = currentNode.next
        } else {
            currentNode.next = new ListNode(l2.val, null);
            l2 = l2.next;
            currentNode = currentNode.next
        }
    }
    while (l1) {
        currentNode.next = new ListNode(l1.val, null);
        l1 = l1.next;
        currentNode = currentNode.next
    }
    while (l2) {
        currentNode.next = new ListNode(l2.val, null);
        l2 = l2.next;
        currentNode = currentNode.next
    }
    return newList.next
};

剑指 Offer 52. 两个链表的第一个公共节点

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

提议理解 两个链表,返回链表中第一个相同的节点,即节点相同,不是节点值相同

  1. 使用Set方法现存A中的每一个节点,再遍历B链表,如果SetA中存在B中的检点则返回此节点,否则返回null

例子 [4, 1, 8, 4, 5] [5, 0, 1, 8, 4, 5] 返回 8

function getIntersectionNode(headA, headB) {
    if (!headA || !headB) {
        return null;
    }
    let currentNode = headA;
    const setA = new Set();
    while (currentNode) {
        setA.add(currentNode.val);
        currentNode = currentNode.next
    }
    currentNode = headB;
    while (currentNode) {
        if (setA.has(currentNode.val)) {
            return currentNode.val
        }
        currentNode = currentNode.next
    }
    return null;
}

双指针法 如果两个链表长度相等,有共同节点,则位置一定相同,否为就是没有共同节点,返回null 长度不等时,当一个为null是指针指向另一个链表,一直循环,直到结束,返回节点

    // [1] [2,1]
    // [] [1]
    // [2,1] []
    // [1] [1]

    // [1,2] [3,4,5,2]

    // 2        2,5,2
    // 3,4,5,2   5,2
    // 4,5,2      2
    // 5,2        1,2
    //  2          2
    function getIntersectionNode(headA, headB) {
        if (!headA || !headB) {
            return null;
        }
        let currentA = headA;
        let currentB = headB;

        while (currentA !== currentB) {
            currentA = currentA ? currentA.next : headB
            currentB = currentB ? currentB.next : headA
        }
        return currentA
    }