美文网首页
LinkedList:两个单链表,返回第一个相交点,假设2个单链

LinkedList:两个单链表,返回第一个相交点,假设2个单链

作者: 敲一手烂代码 | 来源:发表于2016-05-18 13:43 被阅读0次
public Node getIntersectionNode(Node headA, Node headB) {
        if (headA==null||headB==null) {
            return null;
        }
        Node node1 = headA;
        Node node2 = headB;
        int headACount = 0;
        int headBCount = 0;
        while (node1.next!=null) {
            node1 = node1.next;
            ++headACount;
        }
        while (node2.next!=null) {
            node2 = node2.next;
            ++headBCount;
        }
        if (node1!=node2) {
            return null;
        }
        int step = headACount-headBCount;
        if (step>0) {
            while (step>0) {
                headA = headA.next;
                step--;
            }
        } else {
            step = -step;
            while (step>0) {
                headB = headB.next;
                step--;
            }
        }
        while (headA!=headB) {
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }

相关文章

  • LinkedList:两个单链表,返回第一个相交点,假设2个单链

  • 相交链表

    相交链表 编写一个程序,找到两个单链表相交的起始节点。 注意: 如果两个链表没有交点,返回 null. 在返回结果...

  • 相交链表

    编写一个程序,找到两个单链表相交的起始节点。 注意: 如果两个链表没有交点,返回 null.在返回结果后,两个链表...

  • 160. 相交链表

    编写一个程序,找到两个单链表相交的起始节点。注意: 如果两个链表没有交点,返回 null.在返回结果后,两个链表仍...

  • Swift - LeetCode - 相交链表

    题目 相交链表 问题: 编写一个程序,找到两个单链表相交的起始节点。 示例: 说明: 如果两个链表没有交点,返回 ...

  • 160. 相交链表

    给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相...

  • 2022-01-11 160. 相交链表【Easy】

    给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相...

  • Swift刷算法:相交链表

    给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相...

  • 自己用单链表实现的LinkedList

    上面学习了单链表,现在我们用单链表实现LinkedList。实现LinkedList主要就是实现增删改查这几个操作...

  • 链表常用操作的代码实现

    以单链表为例,假设单链表的节点结构为 则单链表的实现如下

网友评论

      本文标题:LinkedList:两个单链表,返回第一个相交点,假设2个单链

      本文链接:https://www.haomeiwen.com/subject/dprwrttx.html