zoukankan      html  css  js  c++  java
  • 求两个链表的第一个公共节点(建模有趣)

    题目描述:

    析:本题如果采用暴力遍历方法的话,最大时间复杂度为O((m + n)* (l + n))

    其实这道题可以建模成一个相遇问题,如上图所示:A和B同时出发,速度均为1,求他们的相遇点p,很明显,当行走路程达到(m + n + l)时,两者路程相同,相遇,代码如下:

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
            ListNode* p1 = pHead1;
            ListNode* p2 = pHead2;
            while(p1 != p2)
            {
                p1 = (p1 == NULL ? pHead2 : p1 -> next);
                p2 = (p2 == NULL ? pHead1 : p2 -> next);
            }
            return p1;
        }
    };
  • 相关阅读:
    Android开发环境
    安卓学习
    Shuffle'm Up POJ
    Duizi and Shunzi HDU
    Find a path HDU
    Cyclic Nacklace HDU
    Keywords Search HDU
    HDU 1495 非常可乐
    J
    Fire Game FZU
  • 原文地址:https://www.cnblogs.com/zf-blog/p/9956602.html
Copyright © 2011-2022 走看看