#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<stdlib.h>
#include"algorithm"
using namespace std;
//链表结点
typedef struct _ListNode{
int data;
struct _ListNode* next;
}ListNode;
//无头节点
ListNode* LinkList_Create(int *value, int num)
{
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
ListNode *pTail = pHead;
pHead->data = value[0];
pHead->next = NULL;
for(int i = 1; i < num; i++)
{
ListNode *pCur = (ListNode*)malloc(sizeof(ListNode));
pCur->data = value[i];
pTail-> next= pCur;
pTail = pCur;
}
pTail->next = NULL;
return pHead;
}
void PrintNode(ListNode *head)
{
ListNode *p = head;
for(;p;p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
/****************************算法***********************************/
//获取链表的长度
int GetListLength(ListNode* pHead)
{
if(pHead == NULL)
{
return 0;
}
ListNode *p = pHead;
unsigned int length = 1;
while(p->next != NULL)
{
p = p->next;
length ++;
}
return length;
}
int FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
{
int ret = 0;
if(pHead1 == NULL || pHead2 == NULL)
{
return NULL;
}
unsigned int len1 = GetListLength(pHead1);
unsigned int len2 = GetListLength(pHead2);
//printf("%d %d\n", len1, len2);
//长短指针 默认pHead1长 pHead2短,如果不是,再更改
ListNode *pHeadLong = pHead1;
ListNode *pHeadShort = pHead2;
int lengthdif = len1 - len2;
//如果pHead2长 pHead1短
if(len1 < len2)
{
pHeadLong = pHead2;
pHeadShort = pHead1;
lengthdif = len2 - len1;
}
//去掉长链表长出的部分
for(int i= 0; i < lengthdif; i++)
{
pHeadLong = pHeadLong->next;
}
//此时pHeadLong 和pHeadShort长度相同
while(pHeadLong != NULL && pHeadShort != NULL )
{
if(pHeadLong->data == pHeadShort->data)
{
ret = pHeadLong->data;
break;
}
else
{
pHeadLong = pHeadLong->next;
pHeadShort = pHeadShort->next;
}
}
return ret;
}
int main()
{
int data1[3] = {4,3,6};
int data2[6] = {1,4,5,2,3,6};
ListNode* pHead1 = LinkList_Create(data1,3);
ListNode* pHead2 = LinkList_Create(data2,6);
PrintNode(pHead1);
PrintNode(pHead2);
int node = FindFirstCommonNode(pHead1, pHead2);
//printf("%d", listnode->data);
cout << node << endl;
return 0;
}
5、两个链表的第一个公共节点
最新推荐文章于 2020-11-19 17:54:44 发布