输入两个链表,找出它们的第一个公共结点。

时间:2021-12-31 11:01:12
/*
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 node1 = pHead1;
        ListNode node2 = pHead2;
        if (pHead1 == null || pHead2 == null)
            return null;
       
        
        Stack<ListNode> stack1 = new Stack<>();
        
        while (node1!=null){
            stack1.push(node1);
            node1 = node1.next;
        }

        Stack<ListNode> stack2 = new Stack<>();
        
        while (node2 != null){
            stack2.push(node2);
            node2 = node2.next;
        }
        ListNode s1 = stack1.pop();
        ListNode s2 = stack2.pop();
        while (!stack1.isEmpty() && !stack2.isEmpty() && s1 == s2){
            s1 = stack1.pop();
            s2 = stack2.pop();
        }
        
        if (stack1.isEmpty()) {
            return pHead1;
        }
        if (stack2.isEmpty()) {
            return pHead2;
        }
        return s1.next;
        
        
    }
}