C++实现栈的基本操作(入栈,出栈,取栈顶)
参考资料:王道数据结构考研复习指导;王道C语言督学营
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 50
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top;
}SqStack;
//栈初始化
void Init_Stack(SqStack& S)
{
S.top = -1;
}
//栈判空
bool isEmpty(SqStack S)
{
if (S.top==-1)
{
return true;
}
return false;
}
//栈判满
bool isFull(SqStack S)
{
if (S.top == MAXSIZE - 1)
{
return true;
}
return false;
}
//入栈
bool Push(SqStack& S, ElemType e)
{
bool flag = isFull(S);
if (flag==true)
{
printf("栈满\n");
return false;
}
S.top++;
S.data[S.top] = e;
return true;
}
//出栈
bool Pop(SqStack& S, ElemType& e)
{
bool flag = isEmpty(S);
if (flag)
{
printf("栈空\n");
return false;
}
e = S.data[S.top];
S.top--;
return true;
}
//取栈顶
bool GetTop(SqStack& S, ElemType& e)
{
bool flag = isEmpty(S);
if (flag)
{
return false;
}
e = S.data[S.top];
return true;
}
//输出栈(栈中元素)
void Print_Stack(SqStack S)
{
int data;
while (isEmpty(S) != true)
{
Pop(S, data);
printf("%-5d", data);
}
printf("\n");
}
//主函数
int main()
{
SqStack S;
bool flag;
ElemType m;//用来存放拿出来的元素(栈顶元素或出栈元素)
printf("初始化……\n");
Init_Stack(S);
flag = isEmpty(S);
if (flag == true)
{
printf("栈是空的\n");
}
printf("入栈:3,4,5,6\n");
Push(S, 3);
Push(S, 4);
Push(S, 5);
Push(S, 6);
flag = GetTop(S, m);
if (flag)
{
printf("获取栈顶元素,值为%d\n", m);
}
flag = Pop(S, m);
if (flag)
{
printf("出栈成功,出栈元素为%d\n", m);
}
flag = GetTop(S, m);
if (flag)
{
printf("获取栈顶元素,值为%d\n", m);
}
printf("打印栈中元素:\n");
Print_Stack(S);
return 0;
}
//参考资料:王道数据结构考研复习指导;王道C语言督学营