@【数据结构】(栈 基本函数)
定义堆栈的相关函数,演示栈的使用,进栈,出栈,判栈空、取栈顶元素等功能。
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
#define MAXN 10 /* 栈的最大容量 */
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType data[MAXN];
int top;
}SqStack;
void InitStack(SqStack &st)
{
st.top = -1;
}
int push(SqStack &st,ElemType x) /* 进栈函数 */
{
if (st.top==MAXN-1) //栈满上溢返回0
return 0;
else
{
st.top++;
st.data[st.top] = x;
return 1;
}
}
int pop(SqStack &st,ElemType &x) /*出栈函数*/
{
if (st.top == -1)
return 0;
else
{
x = st.data[st.top];
st.top--;
return x;
}
}
int EmptyStack(SqStack &st) //判断栈是否为空
{
if (st.top == -1) return -1;
else return 0;
}
int GetTop(SqStack &st,ElemType &x) //获取栈顶元素
{
if (st.top == -1)
return 0;
else
{
x = st.data[st.top];
return x;
}
}
void OutputStack(SqStack &st) /* 输出栈元素 */
{
int i = st.top;//记录st.top
while (st.top != -1)
{
cout << st.data[st.top] << " ";
st.top--;
}
cout << endl;
st.top = i;//还原
}
void main()
{
SqStack st;
InitStack(st);
push(st, 1);
push(st, 2);
push(st, 3);
push(st, 4);
push(st, 5);
cout << "初始时栈为:" << endl;
OutputStack(st);
ElemType x;
int index;
while (1) //永真循环
{
cout << "---------------------------------------------" << endl;
cout << "请选择操作:1:进栈" << endl;
cout << " 2:出栈 " << endl;
cout << " 3:获取栈顶元素 " << endl;
cout << " 4:栈是否为空 " << endl;
cout << " 5:输出栈内元素" << endl;
cout << " 0:退出 " << endl;
cout << "---------------------------------------------" << endl;
cin >> index;
switch (index)
{
case 1:
{
cout << "请输入x:";
cin >> x;
push(st, x); cout << x << "进栈后:";
OutputStack(st); break;
}
case 2:
{
pop(st, x);
cout << "出栈后:" << endl;
OutputStack(st); break;
}
case 3:
{
cout << "栈顶元素为:" << GetTop(st, x) << endl;
break;
}
case 4:
{
cout << "栈空情况(-1为空,0为非空):" << EmptyStack(st) << endl;
break;
}
case 5:
{
cout << "输出栈中元素:" << endl;
OutputStack(st); break;
}
case 0: {break; exit(0); }
}
}
system("pause");
}
测试示例:
进栈:
出栈:
获取栈顶元素:
判栈空:
输出栈内元素: