//用数组表示堆栈
#include<iostream>
#include<bits/stdc++.h>
#define MaxSize 1024 //根据需要定义数组最大空间,此为笔者随意定义
using namespace std;
typedef int ElementType;//ElementType表示任意类型,此处暂用于表示int类型
typedef struct SNode {
ElementType Data[MaxSize] ;
int Top;//栈顶位置
}*Stack;
int Push (Stack PtrS,ElementType x)
{
//先判断是否栈满
if(PtrS->Top>=MaxSize-1)
{
cout<<"栈满"<<endl;
return -1;
}
PtrS->Data[++PtrS->Top]=x;//入栈,顺便将Top往上加
return 0;
}
ElementType Pop(Stack PtrS)
{
//先判断是否栈空
if(PtrS->Top<0)//-1或者别的比零小的下标,问题在于如何初始化
{
cout<<"栈空"<<endl;
return NULL;
}
return (PtrS->Data[PtrS->Top--]);
}
Stack CreateStack()//用于初始化
{
Stack s=(Stack)malloc(sizeof(Stack));//申请空间
s->Top=-1;//初始化为-1
return s;
}
int main()
{
Stack PtrS=CreateStack();
for(int i=0;i<100;i++)
{
Push(PtrS,i+1);
}
for(int i=0;i<100;i++)
{
cout<<Pop(PtrS)<<ends;
if((i+1)%10==0)
cout<<endl;
}
return 0;
}
堆栈的要点是后进先出,用数组实现非常简单