已知两个由正整数组成的无序序列A、B,每个序列的元素个数未知,但至少有一个元素。你的任务是判断序列B是否是序列A的连续子序列。假设B是“1 9 2 4 18”,A是“33 64 1 9 2 4 18 7”,B是A的连续子序列;假设B是“1 9 2 4 18”,A是“33 1 9 64 2 4 18 7”,B不是A的连续子序列。
要求:
建立两个单链表A、B用于存储两个正整数序列,然后按照题目的要求,判断链表B是否是链表A的连续子序列。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。在程序结束前要释放链表A、B中的所有节点
#include <stdio.h>
#include <stdlib.h>
struct listnode
{
int data;
struct listnode *next;
};
typedef struct listnode listnode;
listnode * creatlist()
{
int num;
scanf("%d",&num);
listnode *phead=NULL,*pcur=NULL,*plast=NULL;
while(num!=-1){
pcur=(listnode*)malloc(sizeof(listnode));
if(pcur!=NULL){
pcur->data=num;
}if (phead==NULL){
phead=pcur;
plast=pcur;
}else
{
plast->next=pcur;
plast=pcur;
}//将数据循环写入链表
scanf("%d",&num);
}
plast->next=NULL;
return phead;//结束写入
}
void listfree(listnode ** pphead){
while(*pphead != NULL)
{
listnode * temp = *pphead;
*pphead = (*pphead)->next;
free(temp);
}
*pphead=NULL;
}//释放内存的函数
int match(listnode**ptr1,listnode**ptr2)
{
while(*ptr1!=NULL)
{
if((*ptr1)->data!=(*ptr2)->data){
*ptr1=(*ptr1)->next;
continue;
}//如果数据不匹配,则继续循环
listnode*temp1=*ptr1,*temp2=*ptr2;//保存当前位置
while(temp2!=NULL)
{
if(temp1->data!=temp2->data)
{
*ptr1=(*ptr1)->next;
break;
}
temp1=temp1->next;
temp2=temp2->next;//移动位置,判断下一位是否相等
}
if(temp2==NULL){
printf("ListB is the sub sequence of ListA.");
return 1;
}//若链表B遍历完毕,则说明匹配成功
}
printf("ListB is not the sub sequence of ListA.");
}
int main()
{
listnode*ptr1=creatlist();
listnode*ptr2=creatlist();
match(&ptr1,&ptr2);
listfree(&ptr1);
listfree(&ptr2);
}