北邮2019计导下 链表一 C. 实验11_11_链表匹配

这个题目实际上是改过的,原来的描述就是子序列,我就按照子序列做了,错了再审题才发现要求连续。经群里大佬反映,老师已将题干修正。
创建和删除链表可以照抄之前的程序,匹配的话其实和数组差不了太多。
按老师的命名规则的话,变量名加上Ptr后缀表示一级指针,sPtr后缀表示二级指针(s->supreme2333)。

#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
	int data;
	struct _node* nextPtr;
} Node;

Node* createList();
void destoryList(Node** sPtr);
int subSeqCheck(Node **AsPtr,Node**BsPtr);

int main(int argc, char const *argv[])
{
	Node *Alist=createList();
	Node *Blist=createList();
	if(subSeqCheck(&Alist,&Blist))
		printf("ListB is the sub sequence of ListA.\n");
	else
		printf("ListB is not the sub sequence of ListA.\n");
	destoryList(&Alist);
	destoryList(&Blist);
	return 0;
}

Node* createList()
{
	Node *currentPtr,*headPtr=NULL,*lastPtr;
	int num;
	scanf("%d",&num);
	while(num!=-1)
	{	
		currentPtr=(Node*)malloc(sizeof(Node));
		currentPtr->data=num;
		if(!headPtr)
			headPtr=lastPtr=currentPtr;
		else
		{
			lastPtr->nextPtr=currentPtr;
			lastPtr=currentPtr;
		}
		scanf("%d",&num);
	}
	lastPtr->nextPtr=NULL;
	return headPtr;
}

void destoryList(Node **sPtr)
{
	Node *headPtr=*sPtr,*tmpPtr;
	while(headPtr)
	{
		tmpPtr=headPtr;
		headPtr=headPtr->nextPtr;
		free(tmpPtr);
	}
	*sPtr=NULL;
}

int subSeqCheck(Node **AsPtr,Node**BsPtr)
{
	//A是父列,B是子列,要求A中连续存在B的一段
	Node *AheadPtr=*AsPtr,*BheadPtr=*BsPtr,*AtmpPtr,*BtmpPtr;
	int flag=0,num=BheadPtr->data;//num表示B链表的第一个元素,用于匹配可能的位置
	while(!flag&&AheadPtr)//没有找到并且A还没有遍历完的时候循环
	{
		if(AheadPtr->data==num)//如果对上了第一个数
		{
			AtmpPtr=AheadPtr,BtmpPtr=BheadPtr;//保存当前位置
			while(AtmpPtr&&BtmpPtr)//两者同时遍历,并检查每一个值是否相同
			{
				if(AtmpPtr->data!=BtmpPtr->data)
					break;
				AtmpPtr=AtmpPtr->nextPtr;
				BtmpPtr=BtmpPtr->nextPtr;
			}
			if(!BtmpPtr)//如果成功匹配,那么B应该到了NULL,就找到了
				flag=1;
		}
		AheadPtr=AheadPtr->nextPtr;//第一个数都没匹配上就跳到下一个
	}
	return flag;
}

题目描述
问题描述:已知两个由正整数组成的无序序列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中的所有节点。
输入与输出要求:依次输入两个乱序的正整数序列A、B,序列中元素个数未知,但每个序列至少有一个元素,并以输入“-1”结束,每个序列占一行。如果序列B是序列A的连续子序列,则输出“ListB is the sub sequence of ListA.”,否则输出“ListB is not the sub sequence of ListA.”。
数据最多的测试用例节点数在100这个数量级,所有整数可以用int型存储。
请注意输入输出格式。

输入样例
Sample 1:
5 4 3 2 1 -1
3 2 1 -1

Sample 2:
1 2 3 4 5 6 7 8 9 -1
1 2 3 4 5 6 7 8 0 -1

输出样例
Sample 1:
ListB is the sub sequence of ListA.

Sample 2:
ListB is not the sub sequence of ListA.

猜你喜欢

转载自blog.csdn.net/weixin_43873801/article/details/88591565
今日推荐