描述
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 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 个节点。
思路
- 确定是否存在交点,由于是单链表,如果存在交点,则尾节点必定是同一个节点
- 如果没有交点,返回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;
}
}