两个链表的第一个公共结点

来源:互联网 发布:win10 linux安装教程 编辑:程序博客网 时间:2024/06/07 11:40

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

思路:使用两个栈,将两个链表的元素压入栈,逐步同时弹出,当栈顶元素不同时,刚刚弹出的元素就是它们的第一个公共结点。

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/import java.util.*;public class Solution {    private Stack<ListNode> stack1,stack2;    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        if(pHead1 == null || pHead2 == null)            return null;        stack1 = new Stack();        stack2 = new Stack();        while(pHead1 != null){            stack1.push(pHead1);            pHead1 = pHead1.next;        }        while(pHead2 != null){            stack2.push(pHead2);            pHead2 = pHead2.next;        }        ListNode node = null;        while(!stack1.empty() && !stack2.empty()){            if(stack1.peek() == stack2.peek()){                node = stack1.peek();            }else{                break;            }            stack1.pop();            stack2.pop();        }        return node;    }}
原创粉丝点击