题目描述
编写一个程序,找到两个单链表相交的起始节点。
如图
相交结点为c1
输入AB两个链表
输出c1结点
思路
可以利用数组,将其中一个链表的所有结点引用都存进去,然后再用另一个链表进行循环判断,遇到相同的引用即说明存在交点,返回即可,注意空链表的情况。
代码实现
/**
* 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[] list = new ListNode[500000];
int i = 0;
while (headB != null) {
list[i++] = headB;
headB = headB.next;
}
while (headA != null) {
for (int j = 0; j < i; j++) {
if (headA == list[j]) {
return headA;
}
}
headA = headA.next;
}
return null;
}
}