美文网首页
相交链表

相交链表

作者: 二进制的二哈 | 来源:发表于2019-12-24 23:51 被阅读0次

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:


image.png

在节点 c1 开始相交。

示例 1:


image.png
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

解法一:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int aLen = len(headA);
        int bLen = len(headB);
        if(aLen < bLen){
            //A比B短,让B先走几步
            ListNode tmpB = headB;
            int step = bLen - aLen;
            while(step-- != 0){
                tmpB = tmpB.next;
            }
            return func(headA,tmpB);
        }else if(aLen > bLen){
            //A比B长,让A先走几步
            ListNode tmpA = headA;
            int step = aLen - bLen;
            while(step-- != 0){
                tmpA = tmpA.next;
            }
            return func(tmpA,headB);
        }else{
            //两个一样长
            return func(headA,headB);
        }
    }

    private ListNode func(ListNode headA, ListNode headB){
        //两个同等长度的链表,找到相交的节点
        ListNode tmpA = headA;
        ListNode tmpB = headB;
        while(tmpA != null){
            if(tmpA == tmpB)
                return tmpA;
            tmpA = tmpA.next;
            tmpB = tmpB.next;
        }
        return null;
    }

    private int len(ListNode node){
        int len = 0;
        ListNode tmp = node;
        while(tmp != null){
            len++;
            tmp = tmp.next;
        }
        return len;
    }
}

相关文章

  • 链表--相交链表

    目录[https://www.jianshu.com/p/85e18c21317a] 题号[https://lee...

  • 链表相交的问题(java)

    判断两个无环链表是否相交首先我们要知道相交是什么概念两个链表相交.png现在大家都知道了,两个链表相交,则两个链表...

  • 相交链表

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

  • 相交链表

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

  • 相交链表

    题目 编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: A: a1 → a2...

  • 相交链表

    题目 难度级别:简单 编写一个程序,找到两个单链表相交的起始节点。 如下面的两个链表: 在节点 c1 开始相交。 ...

  • 相交链表

    题目描述:编写一个程序,找到两个单链表相交的起始节点。 示例: 输入:intersectVal = 8, list...

  • 相交链表

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/inte...

  • 相交链表

    编写一个程序,找到两个单链表相交的起始节点。 如下面的两个链表: 在节点 c1 开始相交。 示例 1: 输入:in...

  • leetcode的题目160

    160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: 在节点 c1 开始相交。...

网友评论

      本文标题:相交链表

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