Leetcode#160:相交链表[easy]

描述

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表

在节点 c1 开始相交。

示例

示例 1

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

思路

  1. 确定是否存在交点,由于是单链表,如果存在交点,则尾节点必定是同一个节点
  2. 如果没有交点,返回null,如果有交点,则从头遍历,相等时则相交,如果一直不等,直到一个链表走到末尾,从另一个链表头开始走,最终会相交

代码

package cn.lzx.linkedlist;
 

/**
 *@ClassNameLeetcode160_getIntersectionNode
 *@Description  两链表交点
 *@Author lzx
 *@Date2019/10/28 20:38
 *@Version V1.0
 **/
public class Leetcode160_getIntersectionNode {


    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }


    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //非空检验
        if(headA == null || headB == null){
            return null;
        }
        ListNode firstA = headA;
        ListNode firstB = headB;
        //先判断是否相交
        ListNode l1 = headA;
        ListNode l2 = headB;
        while(l1.next != null){
            l1 = l1.next;
        }
        while(l2.next != null){
            l2 = l2.next;
        }
        if(l1 != l2){
            return null;
        }
        //相交
        while(headA != null && headB!= null){
            if(headA == headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
            if(headA == null){
                headA = firstB;
            }
            if(headB == null){
                headB = firstA;
            }
        }
        return null;
    }


}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值