找到两个链表的公共节点

18 篇文章 0 订阅
    • 题目

有两个链表,它们可能有公共的节点,请返回它们的公共节点。

2.分析

  • 我们获取链表的长度,让长的链表先走,直到与短的链表长度相等;

  • 两个链表同时走,直到相遇;

  • 返回相遇点,如果没有相遇,它自动会返回null;相遇,返回相遇点。

3.代码

import org.w3c.dom.NodeList;

/**
 * Describe:
 * User:lenovo
 * Date:2023-01-05
 * Time:22:57
 */
class Node {
    int val;
    Node next;

    public Node() {

    }
    public Node(int val) {
        this.val = val;
    }
}
class MyLinkedList {
    public Node head;

    public MyLinkedList(Node head) {
        this.head = head;
    }
    public MyLinkedList() {
    }
}
public class Test {
    public static Node judgeEncounter(MyLinkedList listA, MyLinkedList listB){
        //判断是否为空
        if(listA == null  || listB == null || listA.head == null || listB.head ==null) {
            return null;
        }
        //计算长度
        int countA = 0;
        int countB = 0;
        Node nodeA = listA.head;
        Node nodeB = listB.head;
        while(nodeA != null) {
            countA++;
            nodeA = nodeA.next;
        }
        while(nodeB != null) {
            countB++;
            nodeB = nodeB.next;
        }
        //长的链表先走
        nodeA = listA.head;
        nodeB = listB.head;
        int count = 0;
        if(countA > countB) {
            count = countA - countB;
            while(count > 0) {
                nodeA = nodeA.next;
                count--;
            }
        }else {
            count = countB - countA;
            while(count > 0) {
                nodeB = nodeB.next;
                count--;
            }
        }
        //两个链表一起走
        while(true) {
            if(nodeA == nodeB) {
                return nodeA;
            }
            nodeA = nodeA.next;
            nodeB = nodeB.next;
        }
    }
    public static void main(String[] args) {
        Node n1 = new Node(5);
        Node n2 = new Node(8);
        Node n3 = new Node(10);
        Node n4 = new Node(8);
        Node n5 = new Node(5);
        Node n6 = new Node(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        Node n7 = new Node(88);
        Node n8 = new Node(82);
        Node n9 = new Node(12);
        n7.next = n8;
        n8.next = n9;
        //n9.next = n4;
        MyLinkedList listA = new MyLinkedList(n1);
        MyLinkedList listB = new MyLinkedList(n7);
        Node cur = judgeEncounter(listA, listB);
        if(cur != null) {
            System.out.println(cur.val);
        }else {
            System.out.println("null");
        }

    }
}
  • 先判断链表是否为空,为空直接返回null;

  • 计算两个链表的长度;

  • 长的链表先走几步,直到后面的节点数相同;

  • 两个节点向后同时走一步,判断是否相等;最后肯定有一个节点相遇(如果没有公共节点,它们都会在null处相遇),直接返回这个节点。

4.总结

解题的关键是在于让后面要走的节点数相同。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值