AcWing 66. 两个链表的第一个公共结点 java 采用2个辅助栈
原题链接
简单
作者:
joyonline
,
2019-12-20 15:57:13
,
所有人可见
,
阅读 834
java 代码
class Solution {
public ListNode findFirstCommonNode(ListNode headA, ListNode headB) {
Stack<ListNode> a = new Stack();
Stack<ListNode> b = new Stack();
while(headA!=null || headB!=null){
if(headA!=null) {
a.push(headA);
headA = headA.next;
}
if(headB!=null){
b.push(headB);
headB = headB.next;
}
}
ListNode tmp = null;
while(!a.isEmpty() && !b.isEmpty()){
ListNode f = a.pop();
ListNode s = b.pop();
if(f==s){
tmp = f;
}else{
break;
}
}
return tmp;
}
}
a+c+b b+c+a
class Solution {
public ListNode findFirstCommonNode(ListNode headA, ListNode headB) {
ListNode p = headA;
ListNode q = headB;
while(p != q){
if(p!=null) p = p.next;
else p = headB;
if(q!=null) q = q.next;
else q = headA;
}
return p;
}
}