題目描述
public class ListNode {
int val;
ListNode next = null;
this.val = val;
}
}*/
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
//建立棧
Stack<Integer> stack = new Stack<Integer>();
//同時對兩個鏈表開始循環,鏈表元素在棧中存在就返回節點,不存在就把鏈表元素壓棧
while((pHead1 !=null) &&(pHead2 != null)){
if(-1 ==stack.search(pHead1.val)){
stack.push(pHead1.val);
pHead1 = pHead1.next;
}else{
return pHead1;
}
if(-1 ==stack.search(pHead2.val)){
stack.push(pHead2.val);
pHead2 = pHead2.next;
}else{
return pHead2;
}
}
//鏈表1未遍歷完的情況
while(pHead1 !=null){
if(-1 ==stack.search(pHead1.val)){
stack.push(pHead1.val);
pHead1 = pHead1.next;
}else{
return pHead1;
}
}
//鏈表2未遍歷完的情況
while(pHead2 !=null){
if(-1 ==stack.search(pHead2.val)){
stack.push(pHead2.val);
pHead2 = pHead2.next;
}else{
return pHead2;
}
}
return null;
}
}