剑指offer 专项突破版 23、两个链表的第一个重合节点

题目链接

思路一:双指针

如果我们把长的链表多余的头砍去,然后让两个指针分别从双方的头结点出发,那么相遇点就是第一个重合结点

public class Solution {

    int getSize(ListNode head) {
        int size = 0;

        for (; null != head; head = head.next)
            size++;

        return size;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (null == headA || null == headB)
            return null;
        int sizeA = getSize(headA), sizeB = getSize(headB);
        ListNode longHead = sizeA > sizeB ? headA : headB, shortHead = sizeA <= sizeB ? headA : headB;

        for (int i = 0; i < Math.abs(sizeA - sizeB); i++) {
            longHead = longHead.next;
        }

        while (longHead != shortHead) {
            longHead = longHead.next;
            shortHead = shortHead.next;
        }

        return longHead;
    }
}
思路二:哈希表

先遍历一遍第一个链表,把所有结点放入哈希表中,然后遍历第二个链表,遍历过程中查看哈希表中是否存在当前结点,如果存在,那么当前结点就是第一个重合结点,如果直到最后还未出现,那么就是没有重合结点

public class Solution {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (null == headA || null == headB)
            return null;

        Set<ListNode> visited = new HashSet<>();

        while (null != headA) {
            visited.add(headA);
            headA = headA.next;
        }

        while (null != headB) {
            if (visited.contains(headB))
                break;
            headB = headB.next;
        }

        return headB;
    }
}
Go代码
func getIntersectionNode(headA, headB *ListNode) *ListNode {
    if headB == nil || headA == nil {
        return nil
    }

    head1, head2 := headA, headB
    count1, count2 := 1, 1

    for head1 != head2 {
        head1 = head1.Next
        head2 = head2.Next

        if head1 == nil {
            if count1 == 1 {
                count1--
                head1 = headB
            } else {
                return nil
            }
        }
        if head2 == nil {
            if count2 == 1 {
                count2--
                head2 = headA
            } else {
                return nil
            }
        }
    }

    return head1
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值