- 後進先出表
- 棧頂是活動的
- 當棧頂指針爲-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;