#include "stdafx.h"
#include<iostream>//顺序栈
using namespace std;
#define MAXSIZE 1024
typedef struct //定义顺序栈的结构
{
int data[MAXSIZE];
int top;
}sqstack;
void InitalStack(sqstack &st) //1.初始化栈InitalStack(栈名)
{
st.top = -1; //栈为空
}
int Push(sqstack &st, int x) //2.进栈Push(栈名,元素值)
{
if (st.top == MAXSIZE - 1)//栈满的情况
{
return 0;
}
st.top++;//栈长度+1
st.data[st.top] = x;//赋值
return 1;
}
int Pop(sqstack &st) //3.出栈Pop(栈名),返回被出栈的值
{
int e;
if (st.top == -1)
{
return 0;
}
e = st.data[st.top];
st.top--;//栈顶-1
return e;
}
int IsEmpty(sqstack &st) //4.判断栈是否为空
{
return(st.top == -1);
}
int GetTop(sqstack &st) //5.取栈顶元素
{
int e;
if (st.top == -1) //如果栈为空
{
return 0;
}
e = st.data[st.top];//用e返回栈顶元素
return e;
}
int GetLength(sqstack &st) //6.求栈长度
{
return st.top + 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
sqstack s; //定义一个顺序栈
InitalStack(s);//初始化
Push(s, 1);//进栈
Push(s, 2);
Pop(s);//出栈
cout << GetTop(s) << '\n';//取栈顶元素
system("pause");
return 0;
}
c++实现顺序栈
于 2015-04-01 21:10:01 首次发布