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

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

题目解析
如果两个链表有公共结点,那么两个链表公共结点之后的结点也都相同,那么两个链表交叉后一定是一个Y型,所以如果我们将两个链表放到两个栈里边,当我们从栈里边同时出栈两个链表的结点,直到最后一个相同的结点,这是算法1。对于两个不同的链表,有公共结点的话,那么如果我们先遍历一个较长的链表,让两个链表剩下的结点个数相同,那么我们只需要同时遍历两个链表,直到第一个相同的结点。

代码如下:

 public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        ListNode temp = pHead1;
        while (temp != null) {
            stack1.push(temp);
            temp = temp.next;
        }
        temp = pHead2;
        while (temp != null) {
            stack2.push(temp);
            temp = temp.next;
        }
        temp = null;
        ListNode node1 = null;
        ListNode node2 = null;
        while (stack1.size() > 0 && stack2.size() > 0){
            node1 = stack1.pop();
            node2 = stack2.pop();
            if (node1.val == node2.val && node1.next == node2.next){
                temp = node1;
            }else{
                break;
            }
        }
        return temp;
    }
    public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null||pHead2 == null) {
            return null;
        }
        int count1 = 0;
        ListNode p1 = pHead1;
        while (p1!=null){
            p1 = p1.next;
            count1++;
        }
        int count2 = 0;
        ListNode p2 = pHead2;
        while (p2!=null){
            p2 = p2.next;
            count2++;
        }
        int flag = count1 - count2;
        if (flag > 0){
            while (flag>0){
                pHead1 = pHead1.next;
                flag --;
            }
            while (pHead1!=pHead2){
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return pHead1;
        }
        if (flag <= 0){
            while (flag<0){
                pHead2 = pHead2.next;
                flag ++;
            }
            while (pHead1 != pHead2){
                pHead2 = pHead2.next;
                pHead1 = pHead1.next;
            }
            return pHead1;
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值