AdamDuncan

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、效率最低的方法就是使用两层循环,循环遍历比较两个节点是否相同。O(n^2)

2、观察到自从公共子节点之后,后面的链表必定是相同的。所以就可以使用两个栈,逐个放入。弹出的时候,遇到第一个不同的节点。之前的一个节点就是所求的第一个公共子节点。O(n)

如下图所示:

3、从头到尾遍历,计算两个链表的长度。接着在长的链表首部剪去比短的链表长的部分。接着从头到尾逐个按对比较,第一对相同的结点就是一个公共子节点。O(n)

#include<iostream>
#include<cmath>
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode *pHeadPointer1 = pHead1,*pHeadPointer2 = pHead2;
        int count1 = 0, count2 = 0;
        while (pHeadPointer1 != NULL)
        {
            pHeadPointer1 = pHeadPointer1->next;
            count1++;
        }
        while (pHeadPointer2 != NULL)
        {
            pHeadPointer2 = pHeadPointer2->next;
            count2++;
        }
        pHeadPointer1 = pHead1;
        pHeadPointer2 = pHead2;
        if (count1 > count2)
        {
            for (int i = 0; i < count1 -count2; i++)
            {
                pHeadPointer1 = pHeadPointer1->next;
            }
        } else {
            for (int i = 0; i < count2 - count1; i++)
            {
                pHeadPointer2 = pHeadPointer2->next;
            }
        }
        int temp = min(count1, count2);
        for (int i = 0 ;i < temp; i++)
        {
            if (pHeadPointer1->val == pHeadPointer2->val && pHeadPointer1->next == pHeadPointer2->next)
            {
                return pHeadPointer1;
            }
            pHeadPointer1 = pHeadPointer1->next;
            pHeadPointer2 = pHeadPointer2->next;
        }
        return NULL;
    }
};

 

posted on 2017-12-01 12:04  AdamDuncan  阅读(266)  评论(0编辑  收藏  举报