两个链表的第一个公共节点
第三十五题:两个链表的第一个公共节点
题目描述
输入两个链表,找出它们的第一个公共结点。
思路:
①首先要想清楚链表相交的实质问题,相交后的结点全部相同
②考虑到的case情况到底有哪些?链表到底有没有环?
③由于此题是找出第一个公共结点,说明两个链表一定相交
④转换成具体的case,分别进行讨论
⑤两个无环链表相交的第一个公共结点
⑥两个有环链表相交的第一个公共结点
具体实现如下图所示:
解析:
①暴力解:时间复杂度O(n^2),空间复杂度O(1)
②hash表解:时间复杂度O(n),空间复杂度O(n)
③stack栈:时间复杂度O(n),空间复杂度O(n)
④快慢指针:时间复杂度O(n),空间复杂度O(1)
hash表具体实现代码如下:
// hash表解法
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode current1 = pHead1;
ListNode current2 = pHead2;
// 定义HashMap(hash表)
HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
// 遍历pHead1
while (current1 != null) {
hashMap.put(current1, null);
current1 = current1.next;
}
// 遍历pHead2
while (current2 != null) {
if (hashMap.containsKey(current2))
return current2;
current2 = current2.next;
}
return null;
}
}
stack栈具体实现代码如下:
// stack栈解法
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
// 代码的鲁棒性
if (pHead1 == null || pHead2 == null) {
return null;
}
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
// 将pHead1压栈
while (pHead1 != null) {
stack1.push(pHead1);
pHead1 = pHead1.next;
}
// 将pHead2压栈
while (pHead2 != null) {
stack2.push(pHead2);
pHead2 = pHead2.next;
}
// result
ListNode commonListNode = null;
// 栈顶元素依次同时弹出,并记录弹出的结点,直到不相同后返回commonListNode
while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek() ) {
stack2.pop();
commonListNode = stack1.pop();
}
return commonListNode;
}
快慢指针具体实现代码如下:
// 快慢指针解法
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
// 代码的鲁棒性
if (pHead1 == null || pHead2 == null){
return null;
}
// 记录多走了多少步
int k = 0;
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
// 遍历pHead1
while (cur1 != null){
cur1 = cur1.next;
k++;
}
// 遍历pHead2
while (cur2 != null){
cur2 = cur2.next;
k--;
}
// 长链表
ListNode longNode = null;
// 短链表
ListNode shortNode = null;
// 判断哪个链表更长
if (k < 0){
k = Math.abs(k);
longNode = pHead2;
shortNode = pHead1;
}else {
longNode = pHead1;
shortNode = pHead2;
}
// 找到长链表后,先让长链表先走k步
while (longNode != null && shortNode != null){
if (k != 0){
longNode = longNode.next;
k--;
}else {
if (longNode.val == shortNode.val){
return longNode;
}
longNode = longNode.next;
shortNode = shortNode.next;
}
}
return null;
}