找到两个链表的公共节点

    • 题目

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

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.总结

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

### 找到两个链表的第一个公共节点 #### 方法一:哈希集合 (基于引用[^1]) 通过使用 `Map` 或者 `Set` 数据结构来存储其中一个链表的所有节点。随后遍历另一个链表,检查当前节点是否已经存在于集合中。如果存在,则该节点即为两链表的第一个公共节点。 这种方法的时间复杂度为 \(O(m+n)\),其中 \(m\) 和 \(n\) 是两条链表的长度;空间复杂度为 \(O(m)\) 或 \(O(n)\),取决于哪个链表被存入集合中。 ```python def getIntersectionNode(headA, headB): nodes_in_B = set() current_node = headB while current_node is not None: nodes_in_B.add(current_node) current_node = current_node.next current_node = headA while current_node is not None: if current_node in nodes_in_B: return current_node current_node = current_node.next return None ``` --- #### 方法二:双指针法 (基于引用[^2]) 定义两个指针分别指向两个链表头结点。每次移动一步,当到达链表末端时,跳转至另一条链表头部继续前进。这样可以消除两者之间的长度差,在第二次相遇处即是第一个公共节点。 此方法时间复杂度同样为 \(O(m+n)\),而空间复杂度降为了 \(O(1)\)。 ```python def getIntersectionNode(headA, headB): pointerA, pointerB = headA, headB while pointerA != pointerB: pointerA = headB if pointerA is None else pointerA.next pointerB = headA if pointerB is None else pointerB.next return pointerA # 返回值可能是公共节点或者None ``` --- #### 方法三:计算长度差异并调整起始位置 先遍历两条链表得到它们各自的长度,并求出差值。让较长的那个链表先行走这个差距步数后再同步逐一遍历比较各对应节点直至发现相等为止。 这种方式也实现了线性时间和常量级额外内存消耗的目标。 ```python def length(node): count = 0 while node: count += 1 node = node.next return count def getIntersectionNode(headA, headB): lenA, lenB = length(headA), length(headB) shorter = headA if lenA < lenB else headB longer = headB if lenA < lenB else headA diff = abs(lenA - lenB) for _ in range(diff): longer = longer.next while shorter and longer: if shorter == longer: return shorter shorter = shorter.next longer = longer.next return None ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值