链表面试题,查找两个链表的第一个公共节点

本题是一道来自《剑指offer》的题目:输入两个链表,找出它们的第一个公共结点。
本题思路有两个,第一种暴力破解法循环嵌套查找,第二个求差法。

  • 循环嵌套查找
    从第一个链表的头节点开始,在第二个链表找相同的节点,第一次没找到,开始走第一个链表的第二个节点,继续从第二个链表从头开始找,直到找到为止。

    /*
    struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
    };*/
    class Solution {
    public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
    {
        ListNode* cur1 = pHead1;
        ListNode* cur2 = pHead2;
        while(cur1 != NULL)
        {
            cur2 = pHead2;
            while(cur2 != NULL)
            {
                if(cur1 == cur2)
                {return cur1;}
                else cur2 = cur2->next;
            }
            cur1 = cur1->next;
        }
        return NULL;
    }
    };
    
  • 求差法
    先遍历两个链表求出他们的长度,当链表重合时,重合节点的后面的节点长度相同,只有公共节点的前面的节点长度不同,求差,让长的链表先走差值的长度,然后求公共节点就简单许多
    这里写图片描述

    /*
    struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
    };*/
    class Solution {
    public:
    int GetListLength(ListNode*pHead)//求两个链表的长度
    {
        int count=0;
       if(pHead==NULL) 
       {
           return 0;
       }
        ListNode*tmp=pHead;
        while(tmp)
        {
            tmp=tmp->next;
            count++;
        }
        return count;
    }
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
           int list1=GetListLength(pHead1);
           int list2=GetListLength(pHead2);
           ListNode*FirstComment=NULL;
           ListNode*longlist=pHead1;
           ListNode*shortlist=pHead2;
           int diff=list1-list2;
           if(list1<list2)
           {
               diff=list2-list1;
               longlist=pHead2;
               shortlist=pHead1;
           }
            for(int i=0;i<diff;i++)
        {
              longlist=longlist->next;
           }
          while(shortlist!=NULL&&longlist!=NULL)
               {
                 if(shortlist==longlist)
                  {
                      FirstComment=shortlist;
                      break;
                  }
                   shortlist=shortlist->next;
                   longlist=longlist->next;
               }
               return FirstComment;
    }
    };

猜你喜欢

转载自blog.csdn.net/weixin_40853073/article/details/81706773