首页 > 代码库 > C++算法之 找出两个链表的公共节点
C++算法之 找出两个链表的公共节点
题目:输入两个链表,找出它们第一个公共节点。链表节点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
}
方法1:在第一个链表上顺序遍历每一个节点,没遍历一个节点,在第二个链表上顺序遍历每个节点。 O(n^2)
方法2:找到两个链表的长度差,先遍历长链表到短链表的长度处,然后两个链表同时遍历,没遍历依次比较两个节点指针是否相同,
注意是比较节点指针,不是节点的值!
代码:
// 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++算法之 找出两个链表的公共节点
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。