1、栈的顺序存储结构及其实现
#include <iostream>
using namespace std;
typedef int SElemType;
typedef int Status;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef struct SqStack
{
SElemType data[MAXSIZE];
int top;
} SqStack;
Status Push ( SqStack *S , SElemType e){
if ( S-> top == MAXSIZE -1)
{
return ERROR;
}
S->top++;
S->data [ S->top] =e;
return OK;
}
Status Pop ( SqStack *S, SElemType *e){
if (S->top == -1)
{
return ERROR;
}
*e =S->data [S->top];
S->top--;
return OK;
}
void Init( SqStack *S){
(S)->top=-1;
}
int main(){
SqStack *s1=new SqStack;
Init(s1);
Push (s1 , 7);
Push (s1 ,5);
Push (s1 , 3);
Push (s1 , 9);
Push (s1 , 8);
SElemType *temp=new SElemType;
while( Pop(s1, temp)){
cout<<*temp<<" ";
}
cout<<endl;
delete s1;
delete temp;
}
2、栈的链式存储结构及其实现
#include <iostream>
using namespace std;
typedef int SElemType;
typedef int Status;
#define OK 1
#define ERROR 0
typedef struct StackNode
{
SElemType data;
struct StackNode *next;
} StackNode , *pStackNode;
typedef struct LinkStack{
pStackNode top;
int count ;
} LinkStack;
Status Push ( LinkStack *s, SElemType e){
pStackNode newNode=(pStackNode) malloc (sizeof (StackNode));
newNode->data=e;
newNode->next=s->top;
s->top=newNode;
s->count++;
return OK;
}
bool StackEmpty (LinkStack *s){
if ( s->top==NULL) return true;
return false;
}
Status Pop ( LinkStack *s , SElemType& e){
pStackNode p;
if ( StackEmpty (s))
{
return ERROR;
}
e=s->top->data;
p=s->top;
s->top =s->top->next;
free(p);
s->count--;
return OK;
}
void InitStack(LinkStack *s){
s->top=NULL;
s->count=0;
}
int main(){
LinkStack* s1=new LinkStack;
InitStack( s1);
Push (s1 , 7);
Push (s1 ,5);
Push (s1 , 3);
Push (s1 , 9);
Push (s1 , 8);
SElemType temp;
while( Pop(s1, temp)){
cout<<temp<<" ";
}
cout<<endl;
delete s1;
}