第2章 线性表的链式表示
综合应用题 第16题
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e7e09515916176c447c518df0b0868c4.png)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct node {
ElemType data;
int len;
struct node *next;
}LNode, *LinkList;
LinkList LinkListInit() {
LNode *L;
L = (LNode *)malloc(sizeof(LNode));
if (L == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
L->next = NULL;
L->len=0;
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;
L->len++;
}
return L;
}
bool Pattern(LinkList &A,LinkList &B)
{
LNode *pa=A->next,*pb=B->next,*pre=A;
while(pa&&pb){
if(pa->data==pb->data)
{
pa=pa->next;
pb=pb->next;
}
else
{
pre=pre->next;
pa=pre;
pb=B->next;
}
}
if(pb==NULL)
return true;
else
return false;
}
bool SonList(LinkList &A,LinkList &B)
{
LNode *pa=A->next,*pb=B->next;
bool isSonList=false;
while(pa&&pb)
{
if(isSonList)
{
if(pa->data!=pb->data)
{
isSonList=false;
pb=B->next;
}
pb=pb->next;
}
else{
if(pa->data==pb->data)
{
isSonList=true;
pb=pb->next;
}
}
pa=pa->next;
}
if(pb==NULL)
isSonList=true;
else
isSonList=false;
return isSonList;
}
int main() {
LinkList list1, list2,list3, start;
int array1[5] = { 2, 2, 3, 5, 7 };
cout<<"输出单链表的数据:";
list1=LinkListCreatT(array1,5);
for (start = list1->next; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
int array2[3] = { 3,5,7 };
cout<<"输出单链表的数据:";
list2=LinkListCreatT(array2,3);
for (start = list2->next; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
cout<<Pattern(list1,list2);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/21f397ce2f95658ee691b35e0183c496.png)