zoukankan      html  css  js  c++  java
  • LeetCode【160】Intersection of Two Linked Lists

    For example, the following two linked lists:

    A:          a1 → a2
                       ↘
                         c1 → c2 → c3
                       ↗            
    B:     b1 → b2 → b3
    

    begin to intersect at node c1.

    思路比较清晰,首先确定二者的长度并计算长度之差的绝对值dis,让较长链表先走dis步,然后两个指针一起走。如果两个指针相等,则返回,否则当指针达到NULL时,没有交点。

    AC代码如下:

        void getLength(ListNode *head , int& len)
        {
            len =0;
            ListNode* h= head;
            while(h)
            {
                h=h->next;
                len++;
            }
        }
        ListNode *getInsersection(ListNode* headA,ListNode* headB,int lena, int lenb)
        {
            if(!lena || !lenb)
                return NULL;
            //headA and headB are not NULL
            if(lena<lenb)
                return getInsersection(headB,headA,lenb,lena);
            //lena>=lenb
            int dis = lena-lenb;
            ListNode* fir=headA,*sec = headB;
            while(dis)
            {
                fir=fir->next;
                --dis;
            }
            while(fir&&sec)
            {
                if(fir==sec)
                    return fir;
                else
                {
                    fir = fir->next;
                    sec = sec->next;
                }
            }
            return NULL;
            
        }
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int lena=0,lenb=0;
            getLength(headA,lena);
            getLength(headB,lenb);
            return getInsersection(headA,headB,lena,lenb);
        }

     

  • 相关阅读:
    TrieTree的学习
    单调队列(monotonic queue)列与单调栈的学习
    507. Perfect Number
    157. Read N Characters Given Read4
    nsexec
    nsenter
    setjmp
    runc 测试
    cgo setns + libcontainer nsexec
    前端 导出为Excel 数据源为table表格 并且table中含有图片
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4495059.html
Copyright © 2011-2022 走看看