给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
方法一:双重循环,暴力破解
/**
* 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;
for(ListNode curA = headA; curA != null; curA = curA.next){
for(ListNode curB = headB; curB != null; curB = curB.next){
if(curA == curB) return curB;
}
}
return null;
}
}
方法二:使用LinkedList
/**
* 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;
List<ListNode> list = new LinkedList<>();
for(ListNode node = headA; node != null; node = node.next){
list.add(node);
}
for(ListNode nodeB = headB; nodeB != null; nodeB = nodeB.next){
if(list.contains(nodeB)){
return nodeB;
}
}
return null;
}
}