栈是限定仅在表尾进行插入和删除操作的线性表。
#include <iostream>
using namespace std;
#define MAXSIZE 1000
#define OK 1
#define ERROR 0
typedef int Status;
typedef int SElemType;
/* 栈的结构定义:首先是一个线性表,其次仅在表尾(栈顶)进行插入和删除操作
* 下标为0的一段作为栈底
* data存储元素,top表示栈顶位置下标
* 若为空栈,则令top=-1
*/
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStatck;
/* 栈的建立:CreatStack
* 思路:
* 1、空栈的top=-1
* 2、长度length不能超过最大值
* 3、top=length-1
*/
Status CreatStack(SqStatck *S, SElemType length)
{
int i,j;
if (length == 0)
{
cout << "为空栈" << endl;
S->top = -1;
return OK;
}
if (length >= MAXSIZE)
{
cout << "长度超过最大值" << endl;
return ERROR;
}
cout << "依次输入数值:";
for (i = 0; i < length; i++)
{
cin >> j;
S->data[i] = j;
}
S->top = length - 1;
return OK;
}
/* 进栈操作:push,插入元素e
* 思路:
* 1、判断栈是否已满
* 2、top++
* 3、data[top]=e
*/
Status Push(SqStatck *S, SElemType e)
{
if (S->top == MAXSIZE)
{
cout << "栈已满" << endl;
return ERROR;
}
S->top++;
S->data[S->top] = e;
return OK;
}
/* 出栈操作:pop,删除栈顶元素,用e返回
* 思路:
* 1、判断栈是否为空
* 2、e=data[top];
* 3、top--
*/
Status pop(SqStatck *S, SElemType *e)
{
if (S->top == -1)
{
cout << "栈为空" << endl;
return ERROR;
}
*e = S->data[S->top];
S->top--;
return OK;
}
int main()
{
int i,length,e;
int *e1;
e1 = (int *)malloc(sizeof(int));
cout << "输入栈的长度:";
cin >> length;
SqStatck S,S1;
CreatStack(&S, length);
S1 = S;
cout << "出栈:";
for (i = S1.top; i >=0; i--)
{
pop(&S1, e1);
cout << *e1 << ' ';
}
cout << endl;
cout << "输入对原栈插入栈顶的元素:";
cin >> e;
Push(&S, e);
cout << "出栈:";
for (i = S.top; i >= 0; i--)
{
pop(&S, e1);
cout << *e1 << ' ';
}
cout << endl;
return 0;
}
结果为: