问题描述:
试写一个算法,判断依次读入的一个以@为结束的字母序列,是否为形如 “序列1&序列2” 模式的字符序列。其中 序列1 和 序列2 中都不含字符 “&”,且 序列2 是 序列1 的 逆序列。例如:“a+b&b+a” 是属该模式的字符序列,而“1+3&3-1”则不是。
测试数据:
由学生自己确定。注意测试边界数据,例如序列1和序列2均为空串。
代码:
首先创建一个栈:
详细如何建栈的过程可以参考博文:用C语言创建一个栈
#include<stdio.h>
#include<malloc.h>
#define STACK 100
#define STACKINCRMENT 10
typedef char ElementType;
//定义结构体 栈顶指针 栈底指针
typedef struct SqStack{
ElementType *base;
ElementType *top;
int stacksize;
} SqStack;
//初始化栈:
void InitStack(SqStack *S)
{
S->base = (ElementType * ) malloc (STACK * sizeof(ElementType));
if (!S->base)
printf("分配存储空间失败");
S->top = S->base;
S->stacksize = STACK;
//return true;
}
//入栈操作的函数:
void Push(SqStack * S, ElementType e)
{
if (S->top - S->base >= S->stacksize)
{
S->base = (ElementType *) realloc(S->base, (S->stacksize + STACKINCRMENT) * sizeof(ElementType));
if (!S->base)
printf("空间不足");
S->top = S->base + S->stacksize;
S->stacksize += STACKINCRMENT;
}
*S->top++ = e;
}
//出栈操作的函数:
ElementType Pop(SqStack * S)
{
ElementType e;
if(S->top != S->base)
{
e= * --S->top;
return e;
}
}
主函数:
思路:首先,序列1进栈;然后序列1出栈和序列2比较。
int main()
{
SqStack S;
ElementType e,p;
int flag = 0;
InitStack(&S);
scanf("%c",&e);
while(e != '&' && flag == 0)
{
Push(&S, e);
scanf("%c", &e);
}
if(e == '&')
flag = 1;
if(flag == 1){
scanf("%c", &e);
while(e != '@' && S.top != S.base)
{
p = Pop(&S);
if(e != p) {
printf("NO");
return 0;
}
else scanf("%c", &e);;
}
}
printf("YES");
}