剑指offer-两个链表第一个公共结点

36.两个链表第一个公共结点

题目描述

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

解题思路:用两重循环,对第一个链表的每一个结点都进行第二个链表所有结点的遍历,若发现结点相等,则将结点返回

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {    
        while(pHead1!=null)
        {
           ListNode head=pHead2;
            while(head!=null)
            {
                if(pHead1==head)
                    return pHead1;
                else
                    head=head.next;
            }
            pHead1=pHead1.next;
        }
        return null; 
    }

解题思路2:若链表相交,则链表的最后一个结点一定相同,计算出两个链表的长度差d,长的链表先走d步,然后两个链表指针同时走,当结点相等时,则返回此结点。

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null || pHead2==null)
            return null;
        int len1=0;
        int len2=0;
        ListNode head1=pHead1;
        ListNode head2=pHead2;
        while(head1!=null)
        {
            len1++;
            head1=head1.next;
        }
        while(head2!=null)
        {
            len2++;
            head2=head2.next;
        }
        head1=pHead1;
        head2=pHead2;
        if(len1>=len2)
        {
            for(int i=0;i<len1-len2;i++)
            {
                head1=head1.next;
            }
        }
        else
        {
            for(int i=0;i<len2-len1;i++)
            {
                head2=head2.next;
            }
        }
        while(head1!=head2 && head1!=null)
        {
            head1=head1.next;
            head2=head2.next;
        }
        if(head1==null)
            return null;
        else
            return head1;        
    }

解题思路3:由于两个链表的最后一个结点相同,则可以从最后一个结点向前找,直到第一个相同的结点,由于链表只能从前向后查询,所以我们可以用栈来进行上述操作

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         if(pHead1==null || pHead2==null)
             return null;
        Stack<ListNode> stack1=new Stack<>();
        Stack<ListNode> stack2=new Stack<>();
        ListNode node=null;
        while(pHead1!=null)
        {
            stack1.push(pHead1);
            pHead1=pHead1.next;           
        }
        while(pHead2!=null)
        {
            stack2.push(pHead2);
            pHead2=pHead2.next;
        }
        if(stack1.peek()!=stack2.peek())
            return null;
        while(!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek()==stack2.peek())
        {
            node=stack1.pop();
            stack2.pop();
        }
        return node;    
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值