【leetcode160】相交链表

一.问题描述

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

  • 输入: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 个节点。

二.示例代码

public static void main(String[] args) {

        ListNode listNode = new ListNode(4);
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(8);
        ListNode listNode3 = new ListNode(4);
        ListNode listNode4 = new ListNode(5);
        listNode3.next = listNode4;
        listNode2.next = listNode3;
        listNode1.next = listNode2;
        listNode.next = listNode1;

        ListNode listNode5 = new ListNode(5);
        ListNode listNode6 = new ListNode(0);
        ListNode listNode7 = new ListNode(1);
        listNode5.next = listNode6;
        listNode6.next = listNode7;
        listNode7.next = listNode2;

        ListNode result = intersectedList2(listNode, listNode5);
        System.out.println(listNode);
        System.out.println(listNode5);
        System.out.println(result);


    }

    private static ListNode intersectedList(ListNode headA, ListNode headB) {
        ListNode p = headA;
        ListNode q = headB;
        Set<ListNode> set = new HashSet<>();
        while (p != null) {
            set.add(p);
            p = p.next;
        }
        while (q != null) {
            if (set.contains(q)) {
                return q;
            }
            q = q.next;
        }
        return null;
    }


    public static ListNode intersectedList2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode head1 = headA;
        ListNode head2 = headB;
        while (head1 != head2) {
            if (head1 != null) {
                head1 = head1.next;
            } else {
                head1 = headB;
            }

            if (head2 != null) {
                head2 = head2.next;
            } else {
                head2 = headA;
            }
        }
        return head1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值