题目的链接在这里:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
题目大意
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
一、示意图
二、解题思路
暴力判断
暴力
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//这道题的一个思路就是 判断两个的长度 然后让长的先走两者的差值
//再开始遍历
//先进行边界判断
if(headA==null||headB==null)
return null;
//然后开始计算两者的长度
int lenA=0;
int lenB=0;
//好蠢 这边需要重新设置一下
ListNode resultA=headA;
ListNode resultB=headB;
//他们两个就启一个 记录长度的作用
while (resultA!=null){
lenA++;
resultA=resultA.next;
}
// System.out.println("lenA"+lenA);
while (resultB!=null){
lenB++;
resultB=resultB.next;
}
// System.out.println("lenB"+lenB);
//然后进行判断长度
if(lenA>lenB){
//说明headA更长
//先让headA先前进两者的差值
int temp=lenA-lenB;
while (temp>0){
headA=headA.next;
temp--;
}
//然后才开始判断
while (headA!=null&&headB!=null){
//这里不是判断值 而是直接判断这两个是不是一个
if(headA==headB){
//好像是题目的原因
return headA;
}
headA=headA.next;
headB=headB.next;
}
}
//然后进行判断长度
if(lenA<lenB){
//说明headB更长
//先让headB先前进两者的差值
int temp=lenB-lenA;
while (temp>0){
headB=headB.next;
temp--;
}
//然后才开始判断
while (headA!=null&&headB!=null){
if(headA== headB){
return headA;
}
headA=headA.next;
headB=headB.next;
}
}
//然后进行判断长度
if(lenA==lenB){
//然后才开始判断
while (headA!=null&&headB!=null){
if(headA== headB){
return headA;
}
headA=headA.next;
headB=headB.next;
}
}
return null;
}
}