BUPT 实验11

BUPT 实验11,第1张

实验11_11_链表匹配
#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
struct Node
{
	int data;
	struct Node* next;
};
int main()
{
	struct Node* headA = (struct Node*)malloc(sizeof(struct Node));
	struct Node* headB = (struct Node*)malloc(sizeof(struct Node));
	headA->next = NULL;
	headB->next = NULL;
	struct Node* temp;
	int i;
	int countA=0,countB=0,countC=0;
	// 链表A
	temp=headA;
	while(1)
	{
		scanf("%d",&i);
		if(i==-1)
		{
			temp=temp->next;
			break;
		}
		countA++;
		struct Node* p = (struct Node*)malloc(sizeof(struct Node));
		p->data=i;
		p->next=NULL;
		temp->next=p;
		temp=p;
	}
	// 链表B
	temp=headB;
	while(1)
	{
		scanf("%d",&i);
		if(i==-1)
		{
			temp=temp->next;
			break;
		}
		countB++;
		struct Node* p = (struct Node*)malloc(sizeof(struct Node));
		p->data=i;
		p->next=NULL;
		temp->next=p;
		temp=p;
	}
	if(countA<countB)
	{
		printf("ListB is not the sub sequence of ListA.");
		return 0;
	}
	struct Node*pA,*pB;
	temp=headA->next;  //记录链表A 开始比较的点
	while(1)
	{
		countC=0;
		pA=temp;
		pB=headB->next;
		while(1)
		{
			if(pA==NULL||pB==NULL)
			{
				if(countC==countB)
					printf("ListB is the sub sequence of ListA.");
				else
					printf("ListB is not the sub sequence of ListA.");
				return 0;
			}
			else if(pA->data!=pB->data)
				break;
			else if(pA->data==pB->data)
			{
				countC++;  //相同元素的个数
				pA=pA->next;
				pB=pB->next;
			}
			if(countC==countB)
			{
				printf("ListB is the sub sequence of ListA.");
				return 0;
			}
		}
		temp=temp->next;
	}
}
//5 4 3 2 1 -1
//3 2 1 -1

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/578102.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-11
下一篇 2022-04-11

发表评论

登录后才能评论

评论列表(0条)

保存