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

// 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步,然后长序列和短序列一起走,直到两个序列的值相等即可
posted @ 2016-10-14 21:38  wdan2016  阅读(105)  评论(0编辑  收藏  举报