第2章 线性表的链式表示
综合应用题 第22题
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *next;
}LNode, *LinkList;
LinkList LinkListInit() {
LNode *L;
L = (LNode *)malloc(sizeof(LNode));
if (L == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
L->next = NULL;
return L;
}
LinkList LinkListCreatT(ElemType *a, int n) {
LNode *L;
L = LinkListInit();
LNode *r;
r = L;
LNode *p;
for (int i = 0; i < n; i++){
p = (LNode *)malloc(sizeof(LNode));
if (p == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
p->data = a[i];
p->next = r->next;
r->next = p;
r = p;
}
return L;
}
int listLen(LinkList head)
{
int len=0;
while(head->next!=NULL)
{
len++;
head=head->next;
}
return len;
}
void find_arr(LNode *str1,LNode *str2)
{
int len1,len2;
len1=listLen(str1);
len2=listLen(str2);
LNode *p,*q;
for(p=str1->next;len1>len2;len1--)
{
p=p->next;
}
for(q=str2->next;len2>len1;len2--)
{
q=q->next;
}
while(p->next!=NULL&&p->next->data!=q->next->data)
{
p=p->next;
q=q->next;
}
cout<<p->data;
}
int main() {
LinkList list1,list2, start;
int array1[7] = { 1, 2, 6,8,3, 5, 7};
int array2[5] = { 4, 9, 3, 5, 7 };
cout<<"输出单链表的数据:"<<endl;
list1=LinkListCreatT(array1,7);
list2=LinkListCreatT(array2,5);
for (start = list1->next; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
for (start = list2->next; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
find_arr(list1,list2);
return 0;
}