//找出公共结点
两个链表有公共结点的话则其后面的结点都是同一个。
法一:长的链表遍历到与短的链表一样长度后开始两两比较。
法二:链表一的第一个结点与链表二的所有结点比较,以此类推继续比较链表一的第二个结点与链表二的所有结点。
法一:
#include<iostream>
using namespace std;
typedef struct lnode {
int data;
struct lnode* next;
}lnode,*linklist;
int a1[7] = { 1,2,3,4,5,6,7 };
int b1[3] = { 5,6,7 };
int n1 = 7, n2 = 3;
void buildlist(linklist &L,int aa[],int n)//建立两个链表
{
L = (lnode*)malloc(sizeof(lnode));
if (L == NULL)return;
lnode* s, * r =L;
for (int i = 0; i < n; i++) {
s = (lnode*)malloc(sizeof(lnode));
s->data = aa[i];
r->next = s;
r = r->next;
}
r->next = NULL;
}
int length(linklist L)
{
int k = 0;
lnode* s = L->next;
while (s)
{
k++;
s = s->next;
}
return k;
}
linklist findsame(linklist L1, linklist L2)
{
lnode* long1, * short1;
int dist = 0;
int len1 = length(L1);
int len2 = length(L2);
if (len1 > len2) {
long1= L1->next;
short1= L2->next;
dist = len1 - len2;
}
else {
long1= L2->next;
short1= L1->next;
dist = len2 - len1;
}
while (dist--)
{
long1 = long1->next;
}
while (long1)
{
if (long1->data == short1->data && long1->next->data == short1->next->data)
return long1;
else {
long1 = long1->next;
short1 = short1->next;
}
}
return NULL;
}
int main()
{
linklist L1;
linklist L2;
buildlist(L1, a1, 7);
buildlist(L2, b1, 3);
lnode* q = findsame(L1, L2);
cout << q->data;
cout << endl;
return 0;
}
法二:
#include<iostream>
using namespace std;
typedef struct lnode {
int data;
struct lnode* next;
}lnode,*linklist;
int a1[7] = { 1,2,3,4,5,6,7 };
int b1[3] = { 5,6,7 };
int n1 = 7, n2 = 3;
void buildlist(linklist &L,int aa[],int n)//建立两个链表
{
L = (lnode*)malloc(sizeof(lnode));
if (L == NULL)return;
lnode* s, * r =L;
for (int i = 0; i < n; i++) {
s = (lnode*)malloc(sizeof(lnode));
s->data = aa[i];
r->next = s;
r = r->next;
}
r->next = NULL;
}
linklist findsame(linklist L1, linklist L2)
{
lnode* s1 = L1->next;
while (s1)
{
lnode* s2 = L2->next;
while (s2)
{
if (s1->data == s2->data && s1->next->data == s2->next->data)
return s1;
else
{
s2 = s2->next;
}
}
s1 = s1->next;
}
return NULL;
}
int main()
{
linklist L1, L2;
buildlist(L1, a1, 7);
buildlist(L2, b1, 3);
lnode* q = findsame(L1, L2);
cout << q->data;
cout << endl;
return 0;
}