#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <stack>
#define maxSize 100
using namespace std;
/*
Created by HarvestWu on 2018/5/4.
*/
//顺序栈定义
typedef struct
{
int data[maxSize]; //存放栈中元素
int top; //栈顶“指针”
}SqStack; //顺序栈定义
//顺序栈初始化
void initStack(SqStack &st);
//顺序栈判空
int isEmpty(SqStack st);
//顺序栈进栈
int push(SqStack &st,int x);
//顺序栈出栈
int pop(SqStack &st, int &x);
int main()
{
SqStack st;
int x;
initStack(st);
if (isEmpty(st))
printf("栈空\n");
else printf("栈非空\n");
if (push(st,5))
printf("入栈成功\n");
else printf("栈满,不能入栈\n");
if (isEmpty(st))
printf("栈空\n");
else printf("栈非空\n");
if (pop(st, x))
printf("出栈成功,出栈元素为:%d\n",x);
else printf("栈空,不能出栈\n");
return 0;
}
void initStack(SqStack &st)
{
st.top = -1;//设置-1表示为空(能利用下标0的空间)
}
int isEmpty(SqStack st)
{
if (st.top == -1)
return 1;
else
return 0;
}
int push(SqStack &st, int x)
{
if (st.top == maxSize - 1) //栈满,不能入栈
return 0;
st.data[++st.top] = x; //移动“指针”,然后入栈
return 1;
}
int pop(SqStack &st, int &x)
{
if (st.top == -1) //栈空,不能出栈
return 0;
x = st.data[st.top--]; //取出元素,然后移动“指针”
return 1;
}
C++ 实现顺序栈
最新推荐文章于 2023-12-04 22:12:21 发布