1.题目
输入两个链表,找出它们的第一个公共结点。
2.思路
采用2个栈,有公共节点的2个链表呈现Y型,两个链表分别入栈,再分别出栈,最后一个相等的节点,也就是正向的第一个公共节点。
3.代码
/*
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) {
Stack<ListNode> stack1 =new Stack<ListNode> ();
Stack<ListNode> stack2 =new Stack<ListNode> ();
while(pHead1!=null){
stack1.push(pHead1);
pHead1=pHead1.next;
}
while(pHead2!=null){
stack2.push(pHead2);
pHead2=pHead2.next;
}
ListNode rtn=null;
while(!stack1.isEmpty()&&!stack2.isEmpty()&&stack1.peek()==stack2.peek())
{
stack1.pop();
rtn=stack2.pop();
}
return rtn;
}
}