1.两个链表第一个公共子节点问题

题目描述:
输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。
数据范围: n≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)

示例 1:

输入:两个相交链表的两个头结点指针
输出:相交链表交点处结点指针

解题思路1:使用HashMap。先遍历A链表,存储到HashMap中,然后遍历B链表,找出交

    public static ListNode findFirstCommonNodeByMap(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        ListNode current1 = pHead1;
        ListNode current2 = pHead2;

        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while (current1 != null) {
            hashMap.put(current1, null);
            current1 = current1.next;
        }

        while (current2 != null) {
            if (hashMap.containsKey(current2))
                return current2;
            current2 = current2.next;
        }

        return null;
    }

 

解题思路2:使用集合。比如Set集合,与上面HashMap解法比较相似

解题思路3:使用栈。先入栈,出栈,一直找到最晚出栈的相同节点。

解题思路4:双指针法。

    public static ListNode findFirstCommonNodeByCombine(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        while (p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
            if (p1 != p2) {
                if (p1 == null) {
                    p1 = pHead2;
                }
                if (p2 == null) {
                    p2 = pHead1;
                }
            }
        }
        return p1;
    }

python解法:差与双指针法,计算两张表的长度,然后长表先走长度之差的距离,然后再一起走,直到找到相同节点。

    def getIntersectionNode4(self, headA, headB):
        s1, s2 = 0, 0
        p, q = headA, headB
        # 计算长度
        while p:
            p = p.next
            s1 += 1
        while q:
            q = q.next
            s2 += 1
        # 长链表先走,但不确定AB谁长,所以有两个循环,但实际上有至少一个循环不会执行
        p, q = headA, headB
        for i in range(s1 - s2):
            p = p.next
        for i in range(s2 - s1):
            q = q.next
        while p and q and p != q:
            p = p.next
            q = q.next
        return p

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值