找出链表的第一个公共结点
2012-08-27 19:15
260 查看
题目:两个单链表,找出它们的第一个公共结点。
链表的结点定义为:
答:
运行界面如下:
建造长链表用到的listLong.txt为:
建造短链表用到的listShort.txt为:
建造公共链表用到的listCommon.txt为:
链表的结点定义为:
struct ListNode { int m_nKey; ListNode* m_pNext; };
答:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
struct ListNode { int m_nKey; ListNode* m_pNext; };
//构造链表
void CreateList(ListNode *&pHead, fstream &fin, ListNode *pNodeCommon)
{
ListNode *pNode = NULL;
ListNode *pTmp = NULL;
int data;
fin>>data;
while (data)
{
pNode = new ListNode;
pNode->m_nKey = data;
pNode->m_pNext = NULL;
if (NULL == pHead)
{
pHead = pNode;
pTmp = pNode;
}
else
{
pTmp->m_pNext = pNode;
pTmp = pNode;
}
fin>>data;
}
if (NULL != pNode)
{
pNode->m_pNext = pNodeCommon;
}
}
//求链表长度
int ListLength(ListNode *pHead)
{
if (NULL == pHead)
{
return 0;
}
ListNode *pNode = pHead;
int length = 0;
while (NULL!= pNode)
{
length++;
pNode = pNode->m_pNext;
}
return length;
}
//找出链表的第一个公共结点
ListNode* FindFirstCommonNode(ListNode *pFirstHead, ListNode *pSecondHead)
{
ListNode *pShortNode = pFirstHead;
ListNode *pLongNode = pSecondHead;
int lengthShort = ListLength(pShortNode);
int lengthLong = ListLength(pLongNode);
if (lengthShort > lengthLong) //1、求出两个链表的长度
{
int temp = lengthLong;
lengthLong = lengthShort;
lengthShort = temp;
ListNode *PTmp = pShortNode;
pShortNode = pLongNode;
pLongNode = PTmp;
}
int separate = lengthLong - lengthShort;
for (int i = 0; i < separate && NULL != pLongNode; i++) //2、让长度长的链表先遍历两个链表的长度的差值
{
pLongNode = pLongNode->m_pNext;
}
while (NULL != pShortNode && NULL != pLongNode && (pShortNode != pLongNode)) //3、第一个相等的链表结点就是第一个公共结点
{
pShortNode = pShortNode->m_pNext;
pLongNode = pLongNode->m_pNext;
}
if (pShortNode == pLongNode)
{
return pShortNode;
}
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
fstream finShort("listShort.txt");
fstream finLong("listLong.txt");
fstream finCommon("listCommon.txt");
ListNode *pNodeShort = NULL;
ListNode *pNodeLong = NULL;
ListNode *pNodeCommon = NULL;
CreateList(pNodeCommon, finCommon, NULL);
CreateList(pNodeShort, finShort, pNodeCommon);
CreateList(pNodeLong, finLong, pNodeCommon);
ListNode *pFirstCommon = FindFirstCommonNode(pNodeShort, pNodeLong);
if (NULL != pFirstCommon)
{
cout<<"两个链表的第一个公共结点为:"<<pFirstCommon->m_nKey;
}
else
{
cout<<"两个链表没有公共结点";
}
cout<<endl;
return 0;
}
运行界面如下:
建造长链表用到的listLong.txt为:
555 8 9 20 44 33 20 8 4 0
建造短链表用到的listShort.txt为:
7 16 39 0
建造公共链表用到的listCommon.txt为:
555 4 50 77 99 0
相关文章推荐
- 输入两个链表,找出它们的第一个公共结点
- 【剑指offer】输入两个链表,找出它们的第一个公共结点。
- 输入两个链表,找出它们的第一个公共结点。
- 程序员面试题精选100题(35)-找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 两个链表的第一个公共结点-输入两个链表,找出它们的第一个公共结点。
- 输入两个链表,找出它们的第一个公共结点
- 62 找出链表的第一个公共结点
- 找出两个链表中的第一个公共结点
- 【剑指Offer-时间效率的平衡】输入两个链表,找出它们的第一个公共结点。
- 输入两个链表,找出它们的第一个公共结点。
- 算法题5 找出两个链表的第一个公共结点
- 找出链表的第一个公共结点(链表)。
- 输入两个链表,找出它们的第一个公共结点
- 找出两个链表的第一个公共结点
- 输入两个链表,找出它们的第一个公共结点
- 两个单向链表,找出它们的第一个公共结点
- 找出两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点输入两个链表,找出它们的第一个公共结点。