一红淡、概念
棧:棧是一個(gè)先進(jìn)后出的線(xiàn)性表致盟,它要求只在表尾進(jìn)行刪除和插入等操作犀斋。
所以棧其實(shí)就是一個(gè)線(xiàn)性表润努,不過(guò)操作有特殊的要求和限制:
- 元素必須先進(jìn)后出;
- 操作只能在線(xiàn)性表尾進(jìn)行
棧的基本操作只有2個(gè)
- 入棧(Push)
- 出棧(Pop)
棧的結(jié)構(gòu)示意圖(網(wǎng)上找的)
二、棧的實(shí)現(xiàn)
下面介紹如何使用順序表實(shí)現(xiàn)一個(gè)簡(jiǎn)單的棧
(1)定義棧的結(jié)構(gòu)
typedef struct {
DATA data[SIZE+1]; //棧的數(shù)據(jù)元素迫淹,SIZE表示棧大小秘通,數(shù)據(jù)從下標(biāo)1開(kāi)始保存
int top; //棧頂,top=0時(shí)表示棧為空
}SeqStack;
(2)初始化棧
SeqStack *SeqStackinit()
{
SeqStack *p;
if (p=(SeqStack *)malloc(sizeof(SeqStack))) {
p->top = 0;
return p;
}
return NULL;
}
(3)釋放棧
void SeqStackFree(SeqStack *s)
{
if (s)
free(s);
}
(4)判斷棧的狀態(tài)
int SeqStackIsEmpty(SeqStack *s)
{
return (s->top == 0);
}
void SeqStackClear(SeqStack *s)
{
s->top = 0;
}
int SeqStackIsFull(SeqStack *s)
{
return (s->top == SIZE);
}
(5)入棧
int SeqStackPush(SeqStack *s, DATA data)
{
if ((s->top + 1) > SIZE) {
printf("棧溢出\n");
return 0;
}
s->data[++s->top] = data;
return 1;
}
(6)出棧
DATA SeqStackPop(SeqStack *s)
{
if (s->top == 0) {
printf("棧為空\(chéng)n");
exit(0);
}
return (s->data[s->top--]);
}
(7)獲取棧頂元素
DATA SeqStackPeek(SeqStack *s)
{
if (s->top == 0) {
printf("棧為空\(chéng)n");
exit(0);
}
return (s->data[s->top]);
}
打完手工敛熬,可能有不完善或者bug肺稀,只能等以后發(fā)現(xiàn)了再修改了