Java算法_相交链表(LeetCode_Hot100)

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

获得更多?算法思路:代码文档,算法解析的私得。

![在这里插入图片描述](https://img-blog.csdnimg.cn/0a67a53947694b9baa15f0902d903dc7.png

在这里插入图片描述

完整代码


import com.sun.org.apache.xpath.internal.XPathAPI;

/**
 * 2 * @Author: LJJ
 * 3 * @Date: 2023/7/27 14:51
 * 4
 */
 class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class IntersectionOfTwoLinkedLists {

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null|| headB ==null){
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        //在两个链表的交点处相遇,或同时到达链表末尾(null)
        while (pA !=pB){
            //pA到达链表末尾后,从heandB开始继续遍历
            pA = (pA == null) ? headB : pA.next;
            pB = (pB == null) ? headA : pB.next;
        }
        return pA; // 或者 pB,因为它们都指向交点,或者都指向null
    }

    // 创建链表并输出链表内容
    public static void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        // 创建用于演示的链表
        ListNode headA = new ListNode(4);
        headA.next = new ListNode(1);
        headA.next.next = new ListNode(7);
        headA.next.next.next = new ListNode(4);
        headA.next.next.next.next = new ListNode(5);

        ListNode headB = new ListNode(5);
        headB.next = new ListNode(0);
        headB.next.next = new ListNode(1);
        headB.next.next.next = headA.next.next; // 将B的链表连接到A的交点处

        System.out.println("链表A:");
        printLinkedList(headA);

        System.out.println("链表B:");
        printLinkedList(headB);

        // 寻找两个链表的交点
        ListNode intersection = getIntersectionNode(headA, headB);

        if (intersection != null) {
            System.out.println("两个链表相交的部分:");
            printLinkedList(intersection);
        } else {
            System.out.println("没有找到交点节点。");
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值