/* public class ListNode { int val; ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/ import java.util.Stack; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode newNode = null; if(pHead1==null || pHead2==null) return newNode;
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
while(pHead1.next != null) {
stack1.push(pHead1);
pHead1 = pHead1.next;
}
if(pHead1.next == null) {
stack1.push(pHead1);
}
while(pHead2.next != null) {
stack2.push(pHead2);
pHead2 = pHead2.next;
}
if(pHead2.next == null) {
stack2.push(pHead2);
}
boolean flag = true;//是否为第一次
while(!stack1.empty() && !stack2.empty()) {
if(flag) {
if(stack1.lastElement().val == stack2.lastElement().val) {
stack1.pop();
stack2.pop();
flag = false;
}else break;
}else {
if(stack1.lastElement().val == stack2.lastElement().val) {
if(stack1.size()==1 || stack2.size()==1) {
newNode = stack1.pop();
break;
}
stack1.pop();
stack2.pop();
}else{
newNode = stack1.lastElement().next;
break;
}
}
}
return newNode;
}
}