给定两个单链表.编写算法找出两个链表的公共结点
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_TailInsert(LinkList &L) {
int x;
L=(LinkList)malloc(sizeof(LNode));
L->data=999999;
LNode *s, *r=L;
printf("请输入数值\n");
scanf("%d",&x);
while(x!=9999) {
s=(LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r=s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
void print(LinkList L) {
printf("\n");
if(L->next==NULL)
printf("该链表为空");
LNode *p= L->next;
while(p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
}
int Length(LinkList L) {
int count=0;
LNode *p=L->next;
while(p!=NULL) {
count++;
p=p->next;
}
return count;
}
LinkList Serach_lst_Common(LinkList L1,LinkList L2) {
int len1=Length(L1) ,len2=Length(L2);
int dist;
LinkList longList,shortList;
if(len1>len2) {
longList = L1->next;
shortList = L2->next;
dist = len1 - len2;
} else {
longList = L2->next;
shortList = L1->next;
dist = len2 - len1;
}
while(dist--)
longList = longList->next;
while(longList!=NULL) {
if(longList->data==shortList->data)
return longList;
else {
longList = longList->next;
shortList = shortList->next;
}
}
return NULL;
}
int main() {
LinkList L1,L2;
int x;
List_TailInsert(L1);
List_TailInsert(L2);
print(L1);
print(L2);
LinkList commonList;
commonList=(LinkList)malloc(sizeof(LNode));
commonList->data=999999;
commonList->next= Serach_lst_Common(L1,L2);
print(commonList);
return 0;
}
运行效果