zoukankan      html  css  js  c++  java
  • 判断两个链表是否相交

    思路:

    两个链表相交,尾节点必然相等

    #include <stdio.h>
    #include <stdlib.h>
    
    struct list
    {
        int element;
        struct list *next;
    };
    
    //
    //问题:判断两个链表是否相交
    //思路:若两个链表相交,则两个链表的尾节点必然相等
    //
    int func01(struct list *A , struct list *B)
    {
        struct list *pa = A;
        struct list *pb = B;
        while(pa != nullptr)
        {
            pa = pa->next;
        }
        while(pb != nullptr)
        {
            pb = pb->next;
        }
        return (pa->element == pb->element);
    }
    
    //
    //问题:判断链表是否有环
    //思路:通过双指针判断,一前一后,前快后慢,若有环
    //快的可以追上慢的
    //
    int func02(struct list *A)
    {
        struct list *fast = nullptr;
        struct list *slow = nullptr;
        if(A->next == nullptr)
        {
            return 0;
        }
        fast = A->next->next;
        slow = A->next;
        while(fast != nullptr && slow != nullptr)
        {
            if(fast->element == slow->element)
            {
                return 1;
            }
            fast = fast->next;
            slow = slow->next;
        }
        return 0;
    }
    
    int main()
    {
        printf("Hello world!
    ");
        return 0;
    }
    

      

     

    时间复杂度O(nlistA+nlistB)

  • 相关阅读:
    用html5标记一段文章模块
    自定义事件
    html5表单
    对canvas封装的js库
    canvas
    第五周进度总结
    第七周进度总结
    大道至简阅读笔记
    第六周进度总结
    第三周进度总结
  • 原文地址:https://www.cnblogs.com/achao123456/p/12158376.html
Copyright © 2011-2022 走看看