/*给定两个单链表,编写算法找出两个链表的公共结点*/
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList TailCreateList(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
ElemType x;
LNode *r = L;
scanf("%d",&x);
while(x!=9999)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
int getListLen(LinkList L)
{
int count = 0;
LNode *p = L->next;
while(p)
{
count++;
p = p->next;
}
return count;
}
LNode *findCommonLNode(LinkList L1,LinkList L2)
{
int len1 = getListLen(L1);
int len2 = getListLen(L2);
int dist;
LNode *longpoint;
LNode *shortpoint;
if(len1<=len2)
{
longpoint = L2->next;
shortpoint = L1->next;
dist = len2 - len1;
}else{
longpoint = L1->next;
shortpoint = L2->next;
dist = len1 - len2;
}
while(dist--)
longpoint = longpoint->next;
while(longpoint!=NULL)
{
//只有是一个公共结点则后面全是公共结点,呈现Y型
if(longpoint == shortpoint)
return longpoint;
else{
longpoint = longpoint->next;
shortpoint = shortpoint->next;
}
}
return NULL;
}
bool printList(LinkList L)
{
LNode *p = L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
return true;
}
void main()
{
LinkList L1,L2;
TailCreateList(L1);
printf("L1表长为:%d\n",getListLen(L1));
printList(L1);
TailCreateList(L2);
printf("L2表长为:%d\n",getListLen(L2));
printList(L2);
}
查找两个单链表的公共结点
最新推荐文章于 2023-11-06 17:54:06 发布