2. 相交链表
难度级别:简单
题目类型:链表
题目描述:
![](https://img-blog.csdnimg.cn/img_convert/56b4b3b209c787206944ab9fc0c9a625.png)
解题思路:
双指针法:
开始时用临时指针tempA, tempB分别指向headA, headB;
两个临时指针分别从两个链表的起点开始遍历:若其中一个指针到达链表尾部,两指针还没相遇,就将该指针指向另一个链表的头部,继续往下走;
在遍历过程中,因为两个临时指针走的路程是一样的,因此,若两个链表相交,在相交的第一个结点相遇;否则两个结点会同时到达两个链表的尾部,返回结果就是null。
时间复杂度:O(m+n)
空间复杂度:O(1)
哈希表法:
将其中一个链表复制进一个哈希表中,这样用另一个链表与哈希表进行比较,如果哈希表中发现结点相同,该结点就是需要返回的结果;否则返回null。
时间复杂度:O(m+n)
空间复杂度:O(m)
源代码
/**
* 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;
ListNode preA = headA;
ListNode preB = headB;
while(preA != preB)
{
preA = (preA == null) ? headB : preA.next;
preB = (preB == null) ? headA : preB.next;
}
return preA;*/
// 哈希表
if(headA == null || headB == null)
return null;
Set<ListNode> copyA = new HashSet<ListNode>();
ListNode tempA = headA, tempB = headB;
while(tempA != null)
{
copyA.add(tempA);
tempA = tempA.next;
}
while(tempB != null)
{
if(copyA.contains(tempB))
return tempB;
tempB = tempB.next;
}
return null;
}
}