顺序栈检查回文

里面测试函数我是为了验证一个字符串是否是回文序列的,大家也可以把源文件改了,要用字符串就把数组改为字符数组,结构体的数据类型也可以改.
头文件:Stack.h

#define MaxSize 50
typedef struct{
   ElemType data[MaxSize];//存放栈中元素
   int  top;                          //栈顶指针
}SqStack;
//初始化
void InitStack(SqStack &S)
{
	S.top=-1;
}
//判空
bool StackEmpty(SqStack &S)
{
	if(S.top==-1)
		return true;
	else
		return false;
}
//进栈
bool Push(SqStack &S,ElemType x)
{
	if(S.top==MaxSize-1)     //栈空,报错
		return false;
 S.data[++S.top]=x;            //指针先加1,再入栈
 return true;
}
//出栈
bool Pop(SqStack &S,ElemType &x)
{
	if(S.top==-1)
		return false;
	x=S.data[S.top--];  //先出栈,指针再减一
	return true;
}
//读取栈顶元素
bool GetTop(SqStack &S,ElemType &x)
{
	if(S.top==-1)
	  return false;
	x=S.data[S.top];
	return true;
}
//比较两个数组的元素值是否相等
int Equal(int a[],int b[],int n)
{
	int flag=1;
   for(int i=0;i<n;i++)
   {
	   if(a[i]!=b[i])
	   {
		   flag=0;
		   break;
	   }
   }
   return flag;
}

源文件:

typedef int ElemType;
#include<stdio.h>
#include<malloc.h>
#include"Stack.h"
int main()
{
	int x;
	int a[5],b[5];
	SqStack mystack1;
    InitStack(mystack1);
	for(int i=0;i<5;i++);
	{
		scanf("%d",&a[i]);
	}
    for(i=0;i<5;i++)
	{
		Push(mystack1,a[i]);
	}
	for(int j=0; j<5;j++)
	{
       Pop(mystack1,b[j]);
	}
	for( j=0; j<5;j++)
	{
      printf("%d  ",b[j]);
	}
	x=Equal(a,b,5);
	if(x==1)
	{
		printf("这是一个回文");
	}
	else
	{
		printf("这不是回文!!");
	}
	return 0;
}

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43753724/article/details/105469470
今日推荐