两个链表的第一个公共结点

输入两个链表,找出它们的第一个公共结点。

法一:在链表一上顺序遍历每个结点,每遍历一个结点,顺序遍历链表二。时间复杂度为O(mn)

法二:利用两个辅助栈,遍历两个链表,将链表元素放入栈中,从栈顶取,直到两个元素不一致时结束,则对应的就为第一个公共结点,时间复杂度O(m+n),空间复杂度O(m+n)

法三:遍历两个链表求其长度,让长的链表先走若干步,然后在遍历两链表,若元素相等则为公共结点,不等则继续向下遍历。

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        unsigned int len1=getlength(pHead1);
        unsigned int len2=getlength(pHead2);
        ListNode* plong=pHead1;
        ListNode* pshort=pHead2;
        int diff=0;
        if (len1>=len2)
        {
            diff=len1-len2;
            
        }
        else 
        {
            plong=pHead2;
            pshort=pHead1;
            diff=len2-len1;
        }
        for (int i=0;i<diff;i++)
        {
            plong=plong->next;
        }
        while(plong!=NULL&&pshort!=NULL&&plong!=pshort)
        {
            plong=plong->next;
            pshort=pshort->next;
        }
        ListNode* node=plong;
        return node;
    }
    unsigned int getlength(ListNode* pHead)
    {
        if (pHead==NULL)
            return 0;
        ListNode* p=pHead;
        unsigned int num=0;
        while(p!=NULL)
        {
            p=p->next;
            num++;
        }
        return num;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值