首页 > 其他 > 详细

160. 相交链表

时间:2019-12-19 21:45:38      阅读:96      评论:0      收藏:0      [点我收藏+]
1. 题目
编写一个程序,找到两个单链表相交的起始节点

示例1:
输入: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 个节点。

示例2:
输入:intersectVal?= 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
2. 思路
使用set集合,先将A链表添加到set中,再向set中添加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) {
        Set<ListNode> set = new HashSet<>();
        if (headA == null || headB == null){
            return null;
        }
        while (headA != null){
            set.add(headA);
            headA = headA.next;
        }
        while (headB != null){
            boolean flag = set.add(headB);
            if (!flag){
                return headB;
            }else {
                headB = headB.next;
            }
        }
        return null;
    }
}

160. 相交链表

原文:https://www.cnblogs.com/guoguo327/p/12069760.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!