题目描述
输入两个链表,找出它们的第一个公共结点。
解析思路
如果有公共结点,则应该公共结点后面的点都是一样的。
所以我们可以倒过来看,遇到的最后一个相同的结点即是正数第一个相同结点。
利用栈先进后出的特点,设两个栈用来储存两个链表。再来开始比较。
运行代码
import java.util.Stack;
/*
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;
}
Stack<ListNode> stack1 = new Stack<ListNode>();
Stack<ListNode> stack2 = new Stack<ListNode>();
ListNode sameNode = null;
while(pHead1 != null){
stack1.push(pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null){
stack2.push(pHead2);
pHead2 = pHead2.next;
}
while(!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek()){
stack2.pop();
sameNode = stack1.pop();
}
return sameNode;
}
}