- 后进先出表
- 栈顶是活动的
- 当栈顶指针为-1时为空栈
- 栈顶指针最大值为数组定义大小 MAX_SIZE-1
宏定义
//宏定义
#define MAX_SIZE 50
#define FAILED -1
#define SUCCESS 0
typedef char ElemType;
typedef struct SqStack
{
ElemType data[MAX_SIZE];
int top;
}SqStack;
typedef SqStack StackType;
基本操作
//初始化栈
StackType* InitStack()
{
StackType* s = (StackType*)malloc(sizeof(StackType));
s->top = -1;
}
//销毁栈
void DestroyStack(StackType* s)
{
free(s);
}
//栈判空
int StackEmpty(StackType* s)
{
return (s->top == -1);
}
//入栈
int Push(StackType* s, ElemType e)
{
if (s->top == MAX_SIZE - 1) return FAILED;
s->data[++s->top] = e;
return SUCCESS;
}
//出栈
int Pop(StackType* s, ElemType* e)
{
if (s->top == -1) return FAILED;
*e = s->data[s->top--];
return SUCCESS;
}
//得到栈顶元素
int GetTop(StackType* s, ElemType* e)
{
if (s->top == -1) return FAILED;
*e = s->data[s->top];
return SUCCESS;
}
应用
//设计一种方法判断一个字符串是否为对称串
int GetTop(StackType* s, ElemType* e)
{
if (s->top == -1) return FAILED;
*e = s->data[s->top];
return SUCCESS;
}
int JudgeSym(ElemType * str)
{
if (s->top == -1) return FAILED;
*e = s->data[s->top];
return SUCCESS;
}
int JudgeSym(ElemType * str)
{
StackType* s = InitStack();
ElemType a ;
ElemType* e=&a;
for (int i = 0; str[i] != 0; i++)
Push(s, str[i]);
for (int i = 0; str[i] != 0; i++)
{
Pop(s, e);
if (str[i] != (*e))
{
DestroyStack(s);
return FAILED;
}
}
DestroyStack(s);
return SUCCESS;
}
共享栈
- 在设计共享栈时,由于一个数组(MAX_SIZE)有两个端点,两个栈有两个栈底
- 让一个栈的栈底为数组的始端,下标为0
- 另一个栈底为数组的末端,即MAX_SIZE - 1
- 共享栈的4要素
- 栈空:栈1空为 top1==-1 ,栈2空为top2=MAXSIZE;
- 栈满条件:top1==top2-1
- 元素进栈:进栈1操作为top1++,data[top1]=x;进栈2操作为top2–,data[top2]=x;
- 元素出栈:出栈1操作为data[top1]=x,top1–;出栈2操作为data[top1]=x,top1++;
typedef struct DStack
{
ElemType data[MAX_SIZE];
int top1,top2;
}DStack;
设计算法时要需要增加一个形参来进行表示对哪一个栈进行操作;
i=1时,栈1;
i=2时,栈2;