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

本文介绍了一种寻找两个链表中第一个公共节点的方法。通过计算两链表长度差并同步遍历的方式找到交点,提供了完整的C++实现代码。

// test02.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
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) {
        int count1 = 0, count2 = 0,count=0;
        ListNode *p1 = pHead1, *p2 = pHead2;
        ListNode *p=NULL;
        if (pHead1 == NULL || pHead2 == NULL) //如果两个链表有一个链表为空,返回空
            return NULL;

        while (p1!=NULL)//统计两个链表中的元素个数
        {
            count1++;
            p1 = p1->next;
        }
        while (p2!=NULL)
        {
            count2++;
            p2 = p2->next;
        }

        if (count1 > count2) //如果链表1的元素个数多余链表2中的元素个数
        {
            count = count1 - count2;
            while (count--)
            {
                pHead1 = pHead1->next;
            }
            while (pHead1!=NULL&&pHead2!=NULL)//必须保证两个链表都不为空
            {
                if (pHead1->val == pHead2->val)
                {
                    p = pHead1;
                    break;
                }
                else
                {
                    pHead1 = pHead1->next;
                    pHead2 = pHead2->next;
                }
            }       
        }
            
        else//如果链表2的元素个数多余链表1中的元素个数
        {
            count = count2 - count1;
            while (count--)
            {
                pHead2 = pHead2->next;
            }
            while (pHead1 != NULL&&pHead2 != NULL)
            {
                if (pHead1->val == pHead2->val)
                {
                    p = pHead1;
                    break;
                }
                else
                {
                    pHead1 = pHead1->next;
                    pHead2 = pHead2->next;
                }
            }

            

        }
        return p;
    }
};

int main()
{
    ListNode a(1);
    ListNode b(2);
    ListNode c(3);
    ListNode d(4);
    ListNode e(5);
    ListNode f(6);
    ListNode g(7);
    ListNode h(8);
    a.next = &b;
    b.next = &c;
    c.next = &f;
    f.next = &g;
    g.next = &h;
    d.next = &e;
    e.next = &f;

    Solution so;
    ListNode *p1 = &a;
    ListNode *p2 = &d;

ListNode *ln=so.FindFirstCommonNode(p1,p2);


    //while (p1!=NULL)
    //{
    //  cout << p1->val << "  ";
    //   p1 = p1->next;
    //}
    //cout << endl;
    //while (p2 != NULL)
    //{
    //  cout << p2->val << "  ";
    //  p2 = p2->next;
    //}

    cout << "第一个公共的节点是:" <<ln->val << endl;

return 0;
}

分析:先算出长的序列比短的序列多n个,然后长的序列先走n步,然后长序列和短序列一起走,直到两个序列的值相等即可

转载于:https://www.cnblogs.com/wdan2016/p/5962189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值