数据结构-链表-相交链表
题目描述
示例
直接分析
我们说过,线性结构,双指针策略是一个利器,但本题又同时是一个判断重复问题,对于判断重复问题,我们有专用的策略-哈希表,这两种方法我都会阐述
哈希表法
哈希表的算法,思维非常简单,但是是以空间为代价的,请看代码
/**
* 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) {
Set<ListNode> set = new HashSet<>() ;
while (headA!=null){
set.add(headA) ;
headA = headA.next ;
}
while (headB!=null){
if (set.contains(headB)) return headB ;
headB = headB.next ;
}
return null ;
}
}
- 我们把第一个链表的所有结点扔到哈希表中,再根据哈希表,判断链表二中哪个结点是哈希表中存在的,此结点为交点
- 时间复杂度为
O(n+m)
因为对两个链表都作了完全遍历 - 空间复杂度为
O(m)
或O(n)
,这取决于你对哪个链表建立哈希
双指针
如果不想以空间为代价,考虑双指针,代码很简单,请看,关键你得有这个意识:
- 如果两个链表相交,那么相交点之后的长度是相同的
我们需要做的事情是,让两个链表从距离末尾同等的距离位置开始遍历。这个位置只能是较短链表的头结点位置。
为此,我们必须消除两个链表的长度差
随便画个图解释一下
看代码
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA