C++ 解决求两个链表的第一个公共结点问题

本文主要介绍了利用C++实现输入两个无环的单向链表时,找出它们的第一个公共结点的问题。文章中的示例代码简洁易懂,感兴趣的同学可以和小编一起学习一下

补充

通过C++找出两个链表的所有公共结点:


// FindFirstCommandNode.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <iostream>
using namespace std;
 
struct ListNode
{
	int         m_nKey;
	ListNode*   m_pNext;
 
	ListNode(int i):m_nKey(i)
	{
 
	}
};
 
//获取链表长度
int GetListLength(ListNode* pHead)
{
	int nLength = 0;
	ListNode* pNode = pHead;
	while (pNode != NULL)
	{
		++nLength;
		pNode = pNode->m_pNext;
	}
	return nLength;
}
 
ListNode* FindFirstCommandNode(ListNode* pHead1, ListNode* pHead2)
{
 
	int  nLength1 = GetListLength(pHead1);
	int  nLength2 = GetListLength(pHead2);
	int nLengthDif = 0;//两个链表的长度差
	ListNode* pListHeadLong  = NULL;//用于指向长链表
	ListNode* pListHeadShort = NULL;//用于指向短链表
 
	//根据长度判断 链表指向
	if (nLength1 > nLength2)
	{
	    nLengthDif = nLength1 - nLength2;
		pListHeadShort = pHead2;
		pListHeadLong  = pHead1;
	}
	else
	{
		nLengthDif = nLength2 - nLength1;
		pListHeadLong  = pHead2;
		pListHeadShort = pHead1;
	}
 
	//先对长链表进行移动 移动到与短链表长度相同的位置
	for (int i = 0; i < nLengthDif; i++)
	{
		pListHeadLong = pListHeadLong->m_pNext;
	}
	//寻找公共节点
	while (pListHeadLong !=NULL && pListHeadShort != NULL && pListHeadLong!= pListHeadShort)
	{
		pListHeadLong  = pListHeadLong->m_pNext;
		pListHeadShort = pListHeadShort->m_pNext;
	}
	//如果不为空  此时的pListHeadLong 与pListNodeShort为同一个节点,返回该节点
	if (pListHeadLong != NULL)
	{
		return pListHeadLong;
	}
	else
	{
		return NULL;//否则返回NULL
	}
}
 
 
int _tmain(int argc, _TCHAR* argv[])
{
 
 
	ListNode* head1 = new ListNode(0);
	ListNode* head2 = new ListNode(1);
	ListNode* node0 = new ListNode(22);
	ListNode* node1 = new ListNode(2);
	ListNode* node2 = new ListNode(3);
	ListNode* node3 = new ListNode(4);
	ListNode* node4 = new ListNode(5);
	ListNode* node5 = new ListNode(6);
	ListNode* node6 = new ListNode(7);
	ListNode* node8 = new ListNode(6);
 
	head1->m_pNext = node1;
	node1->m_pNext = node0;
	node0->m_pNext = node3;
	node3->m_pNext = node5;
	node5->m_pNext = node6;
	node6->m_pNext = NULL;
 
 
 
	head2->m_pNext = node2;
	node2->m_pNext = node4;
	node4->m_pNext = node8;
	node8->m_pNext = node6;
	node6->m_pNext = NULL;
 
	cout<<"链表1的长度为:"<<GetListLength(head1)<<endl;
	cout<<"链表2的长度为:"<<GetListLength(head2)<<endl;
 
 
	ListNode* CommNode = FindFirstCommandNode(head1,head2);
	if (CommNode!= NULL)
	{
		cout<<"公共节点的值为:"<<CommNode->m_nKey<<endl;
	}
	else
	{
		cout<<"没有公共节点"<<endl;
	}
	getchar();
	return 0;
}

到此这篇关于C++ 解决求两个链表的第一个公共结点问题的文章就介绍到这了,更多相关C++ 求两个链表的公共结点内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!

本文标题为:C++ 解决求两个链表的第一个公共结点问题