LeetCode练习题—两个链表的第一个公共结点(Java)

题目描述:

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

注意:

1、如果两个链表没有交点,返回 null.
2、在返回结果后,两个链表仍须保持原有的结构。
3、可假定整个链表结构中没有循环。

示例:

在这里插入图片描述

思路:

输入两个链表,找出它们的第一个公共节点,可以分情况讨论:

1、若任意一个链表为空,那么直接返回null;
2、若为一般情况,要找公共起点,那么可以先让两个链表的长度保持一致;首先分别获取两个的长度 lenA 和 lenB,找到较长的链表longHead,让他向后走step(step= lenA - lenB)步(假设lenA > lenB),此时两个链表长度一致,然后在两个链表不为空,且两链表结点不同的情况下,让两个链表同步向后走;若遇到相同的结点即返回;此时的结点即为两个链表的第一个公共结点

代码:

/**
* Definition for singly-linked list.
* public class Node {
*     int val;
*     Node next;
*     Node(int x) {
*         val = x;
*         next = null;
*     }
*     }
*/
public Node getIntersectionNode(Node headA, Node headB) {
    //任意一个链表为空直接返回null
    if(headA == null || headB == null){
            return null;
        }
    int lenA = getLength(headA);
    int lenB = getLength(headB);
    int step = lenA - lenB;
    Node longHead = headA;
    Node shortHead = headB;
    //判断连个链表之间那个链表更长
    if(step<0){  
        longHead = headB;
        shortHead = headA;
        step = lenB - lenA;
    }
    //长链表向后走至两个链表相同
    for(int i = 0;i<step;i++){  
        longHead = longHead.next;;
    }
    //找到第一个公共结点
    while (longHead != null && shortHead != null && longHead != shortHead) {
        longHead = longHead.next;
        shortHead = shortHead.next;
    }
    return longHead;
}

//获取链表的长度
private int getLength(Node head){
    int count = 0;
    while(head != null){
        head = head.next;
        count++;
    }
    return count;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值