题目:
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
图示两个链表在节点 c1
开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
解法1:使用hashSet存储,另一个遍历找存在
代码:
/**
* 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) {
//使用hashSet
Set<ListNode> visited = new HashSet<>();
ListNode temp = headA;
while (temp != null) {
visited.add(temp);
temp = temp.next;
}
//对B链表遍历寻找是否与A有相同
ListNode temp1 = headB;
while (temp1 != null) {
if (visited.contains(temp1)) {
return temp1;
}
temp1 = temp1.next;
}
//结束都没有为null
return null;
}
}
关键点:
1.思路:使用set存储一个,遍历另一个。包含就是交点
解法2:双指针。结尾相同,补全长度
代码:
/**
* 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 pA = headA;
ListNode pB = headB;
//补全长度
//leetcode写法:
// while (pA != pB) {
// // pA = pA == null ? headB : pA.next;
// // pB = pB == null ? headA : pB.next;
// }
// return pA;
// 让pA和pB分别遍历A+B和B+A
while (pA != null || pB != null) {
if (pA == null) {
pA = headB; // pA走到A的末尾,转到B的头
}
if (pB == null) {
pB = headA; // pB走到B的末尾,转到A的头
}
// 如果pA和pB相遇,则返回交点
if (pA == pB) {
return pA;
}
// 移动指针
pA = pA.next;
pB = pB.next;
}
// 如果没有交点,返回null
return null;
}
}
关键点:
1.思路:使用双指针分别指向第一个点。逐步移动比较。如果不一样长,那就补齐,补齐就是使用另一个链表。题目需要找相同的值,两个链表的尾端一定是相同的。