順序存儲結構來實現的棧稱爲順序棧,它利用一組地址連續的存儲單元存放自棧底到棧頂的數據元素,同時附設一個指針top
來指示當前棧頂的位置。
(注意,“&”是c++
特有的用來表示引用調用,所以此文件應以.cpp
後綴保存)
結構體爲:
#define MaxSize 50
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
基本方法爲:
void InitStack(SqStack &s); //初始化
bool StackEmpty(SqStack &s); //判空
bool Push(SqStack &s, ElemType e); //入棧
bool Pop(SqStack &s, ElemType &e); //出棧
bool GetTop(SqStack s, ElemType &e); //獲取棧頂元素
一個測試函數main()如下所示:
int main()
{
int s, i = 0;
SqStack sqStack;
InitStack(sqStack);
scanf("%d", &s);
while(s != 9999)
{
Push(sqStack, s);
scanf("%d", &s);
}
Pop(sqStack, i);
GetTop(sqStack, s);
printf("%d", s);
return 0;
}
運行結果爲:
完整的源程序爲:
#include "stdio.h"
#include "stdlib.h"
#define MaxSize 50
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &s);
bool StackEmpty(SqStack &s);
bool Push(SqStack &s, ElemType e);
bool Pop(SqStack &s, ElemType &e);
bool GetTop(SqStack s, ElemType &e);
bool ClearStack(SqStack &s);
int main()
{
int s, i = 0;
SqStack sqStack;
InitStack(sqStack);
scanf("%d", &s);
while(s != 9999)
{
Push(sqStack, s);
scanf("%d", &s);
}
Pop(sqStack, i);
GetTop(sqStack, s);
printf("%d", s);
return 0;
}
void InitStack(SqStack &s)
{
s.top = -1;
}
bool StackEmpty(SqStack &s)
{
if(s.top == -1)
return true;
else
return false;
}
bool Push(SqStack &s, ElemType e)
{
if(s.top == MaxSize - 1)
return false;
s.data[++s.top] = e;
return true;
}
bool Pop(SqStack &s, ElemType &e)
{
if(s.top == -1)
return false;
e = s.data[s.top--];
return true;
}
bool GetTop(SqStack s, ElemType &e)
{
if(s.top == -1)
return false;
e = s.data[s.top];
return true;
}