题目
输入两个链表,找出它们的第一个公共结点。
题目分析
有两个链表,首先判断链表是否为空,如果都不为空,以其中一个链表为基础,遍历另一个链表,逐个进行比较。时间复杂度为O(n^2)。
代码实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
// 如果存在空链表,说明没有公共结点
if(pHead1 == null || pHead2 == null){
return null;
}
// 以链表pHead1作为基本链表,取一个结点与pHead2中的所有结点进行比较
ListNode target = pHead1;
while(target != null){
// 避免修改pHead2
ListNode current = pHead2;
while(current != null){
if(target == current){
return target;
}
current = current.next;
}
target = target.next;
}
return null;
}
}
优化方法1:hash法
- 初级方法虽然可以完成任务,但是时间复杂度较高,为了降低时间复杂度,我们采用Hash法。即通过将第二个链表存入HashMap中,遍历第一个链表,查看该结点是否在HashMap中来判断。时间复杂度为O(m+n),空间复杂度为O(n).
- 代码实现
import java.util.Map;
import java.util.HashMap;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null){
return null;
}
// 将第二个链表存入HashMap中
Map<ListNode,Integer> map = new HashMap<>();
while (pHead2 != null){
map.put(pHead2,2);
pHead2 = pHead2.next;
}
// 遍历第一个链表,查找相同结点
while (pHead1 != null){
if (map.get(pHead1) != null){
return pHead1;
}
pHead1= pHead1.next;
}
return null;
}
}