栈的基本概念
栈是一种只能在一端进行插入或删除操作的线性表。其中允许进行插入或删除操作的一端称为栈顶(Top)。栈顶是由一个称为栈顶指针的位置指示器来指示,它是动态变化的。表的另一端称为栈底,栈底是固定不变的。
特点:
先进后出(FILO)
主要实现代码:
#include<stdio.h>
#include<stdlib.h>
#define maxSize 100
typedef struct //定义顺序栈结构体
{
char data[maxSize];
int top;
}SqStack; //[stæk]
void InitStack(SqStack * &s)//初始化顺序栈 initiate 英[ɪˈnɪʃieɪt] 开始, 创始,开辟
{
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1;
}
void DestroyStack(SqStack * &s)//销毁顺序栈 destroy [dɪˈstrɔɪ]杀死; 破坏,摧毁;
{
free(s);
}
bool StackEmpty(SqStack * &s)//判断是否为空表 empty[ˈempti]空的,空虚的,空洞的;
{
return(s->top == -1);
}
bool Push(SqStack * &s, char e)//进栈,push 按; 推动
{
if (s->top == maxSize - 1)
return false;
s->top++;
s->data[s->top] = e;
return true;
}
bool Pop(SqStack * &s, char &e)//出栈,pop出现; 突然出现;
{
if (s->top == -1)
return false;
e = s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack *s, char &e)//取栈顶元素
{
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
bool symmetry(char str[])//用顺序栈检测字符串是否对称symmetry[ˈsɪmətri]对称; 对称美
{
int i;char e;
SqStack *s;
InitStack(s);
for (i = 0; str[i] != '\0'; i++)
{
Push(s,str[i]);
}
for (i = 0; str[i] != '\0'; i++)
{
Pop(s, e);
if (str[i] != e)
{
DestroyStack(s);
return false;
}
DestroyStack(s);
return true;
}
}
int main()
{
char a[] = "woshiihsow";
if (symmetry(a))
printf("这是对称的字符串\n");
else
printf("该字符串不对称\n");
system("pause");
return 0;
}