• 【剑指offer】面试题37:两个链表的第一个公共结点


    题目:

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

    思路:

    由链表的定义知是单链表。对于单链表,如果两个链表有公共结点,则两个链表必然是像Y型相交。则先计算出各个链表的长度,让长链表的头指针先走多出来的几步,再同时让两个链表的指针移动,则判断两个指针是否相等即可。

    代码:

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
            if(pHead1==NULL || pHead2==NULL)  return NULL;
                
            int len1=GetListLength(pHead1);
            int len2=GetListLength(pHead2);
            int diff=len1-len2;
            
            ListNode* head1=pHead1;
            ListNode* head2=pHead2;
            if(diff>0)
            {
                head1=GoNStep(pHead1,diff);
            }
            else 
                head2=GoNStep(pHead2,-diff);
            
            while(head1!=NULL)
            {
                if(head1==head2)  return head1;
                head1=head1->next;
                head2=head2->next;
            }
            
            return NULL;
        }
    private:
        ListNode* GoNStep(ListNode *pHead, int n)
        {
            for(int i=0;i<n;++i)
                if(pHead)  pHead=pHead->next;
            return pHead;
        }
            
        int GetListLength(ListNode *pHead)
        {
            int len=0;
            while(pHead!=NULL)
            {
                len++;
                pHead=pHead->next;
            }
            return len;
        }
    };
  • 相关阅读:
    Java 浮点数精度丢失
    旧梦。
    luogu6584 重拳出击
    luogu1758 [NOI2009]管道取珠
    luogu4298 [CTSC2008]祭祀
    bzoj3569 DZY Loves Chinese II
    AGC006C Rabbit Exercise
    bzoj1115 [POI2009]石子游戏Kam
    luogu5675 [GZOI2017]取石子游戏
    bzoj3143 [HNOI2013]游走
  • 原文地址:https://www.cnblogs.com/buxizhizhou/p/4727884.html
Copyright © 2020-2023  润新知