如果两个链表存在公共结点的话,那么从这个节点开始两个链表的元素值都是相同的。
如果正常的思路需要遍历两个链表来寻找公共节点,那么时间复杂度为O(mn)。
如果从链表尾部开始遍历的话,最后一个相同的元素则是两个链表的第一个公共结点。但是单向链表中只能从头结点开始顺序遍历,所以借助栈的后进先出来解决。这样时间与空间复杂度均为O(m+n)。
import java.util.Stack;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
if(pHead1 == pHead2)
return pHead1;
Stack<ListNode> s1 = new Stack<>();
Stack<ListNode> s2 = new Stack<>();
while (pHead1 != null){
s1.push(pHead1);
pHead1 = pHead1.next;
}
while (pHead2 != null){
s2.push(pHead2);
pHead2 = pHead2.next;
}
ListNode commonNode = null;
while(!s1.isEmpty() && !s2.isEmpty() && s1.peek() == s2.pop()){
commonNode = s1.pop();
}
return commonNode;
}
}