题目描述
输入两个链表,找出它们的第一个公共结点。
import java.util.Stack;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
ListNode node1 = pHead1;
ListNode node2 = pHead2;
Stack<ListNode> stack1 = new Stack<ListNode>();
Stack<ListNode> stack2 = new Stack<ListNode>();
while(node1 != null) {
stack1.push(node1);
node1 = node1.next;
}
while(node2 != null) {
stack2.push(node2);
node2 = node2.next;
}
ListNode node = null;
while(!stack1.isEmpty() && !stack2.isEmpty()) {
node1 = stack1.pop();
node2 = stack2.pop();
if(node1.val != node2.val)
break;
node = node1;
}
return node;
}
}