两个链表的第一个公共节点

题目

输入两个链表,找出它们的第一个公共节点。

分析

在这里插入图片描述

代码在这里插入图片描述
class ListNode{
    public int data;
    public ListNode next;

    public ListNode(int data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "data=" + data +
                '}';
    }
}
import java.util.Stack;

public class Solution {

    public static void main(String[] args) {
        //链表1
        ListNode head = new ListNode(8);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(8);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        //链表2
        ListNode head2 = new ListNode(4);
        ListNode node6 = new ListNode(1);
        ListNode node7 = new ListNode(8);
        head2.next = node6;
        node6.next = node7;
        node7.next = node2;
        System.out.println(getIntersectionNode(head,head2));
    }

    /**
     * 寻找两个链表的第一个公共节点
     * @param headA 链表
     * @param headB 链表
     * @return 第一个公共节点
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Stack<ListNode> stackA = ListNode2Stack(headA);
        Stack<ListNode> stackB = ListNode2Stack(headB);
        ListNode temp = null;
        while (!stackA.isEmpty() && !stackB.isEmpty()){
            if(stackA.peek() == stackB.peek()) {
                stackA.pop();
                temp = stackB.pop();
            }
            else {
                break;
            }
        }
        return temp;
    }

    /**
     * 遍历单向链表 将每个节点压入栈中
     * @param head
     */
    public static Stack<ListNode> ListNode2Stack(ListNode head){
        Stack<ListNode> stack = new Stack<ListNode>();//创建栈
        while (head != null){
            stack.add(head);//将每个节点添加到栈中
            head = head.next;
        }
        return stack;
    }
}
分析

在这里插入图片描述

代码
public class Solution {

    public static void main(String[] args) {
        //链表1
        ListNode head = new ListNode(8);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(8);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        //链表2
        ListNode head2 = new ListNode(4);
        ListNode node6 = new ListNode(1);
        ListNode node7 = new ListNode(8);
        head2.next = node6;
        node6.next = node7;
        node7.next = node2;
        System.out.println(getIntersectionNode(head,head2));

    }

    /**
     * 寻找两个链表的第一个公共节点
     * @param headA 链表
     * @param headB 链表
     * @return 第一个公共节点
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getListLength(headA);//链表长度
        int lenB = getListLength(headB);
        //链表1长度大于链表2
        if (lenA > lenB){
            //先将链表1向前走 lenA-lenB
            for (int i = 0; i < lenA-lenB; i++){
                headA = headA.next;
            }
        }else {
            for (int i = 0; i < lenB-lenA; i++){
                headB = headB.next;
            }
        }
        for (int i = 0; i < Math.min(lenA,lenB); i++){
            if (headA == headB){
                break;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }

    /**
     * 获取链表长度
     * @param head 头节点
     * @return 链表长度
     */
    public static int getListLength(ListNode head){
        int count = 0;
        while (head != null){
            count++;
            head = head.next;
        }
        return count;
    }
分析

在这里插入图片描述

代码
public class Solution {

    public static void main(String[] args) {
        //链表1
        ListNode head = new ListNode(8);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(8);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        //链表2
        ListNode head2 = new ListNode(4);
        ListNode node6 = new ListNode(1);
        ListNode node7 = new ListNode(8);
        head2.next = node6;
        node6.next = node7;
        node7.next = node2;
        System.out.println(getIntersectionNode(head,head2));

    }
    /**
     * 寻找两个链表的第一个公共节点
     * @param headA 链表
     * @param headB 链表
     * @return 第一个公共节点
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node1 = headA;
        ListNode node2 = headB;
        //同时遍历两个链表
        while (node1 != node2){
            node1 =  node1 == null? headB : node1.next;
            node2 =  node2 == null? headA : node2.next;
        }
        return node1;
    }

}
### 找到两个链表第一个公共节点 #### 方法一:哈希集合 (基于引用[^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、付费专栏及课程。

余额充值