//
//SqStack.h
//顺序栈的基本运算
//2013-10-12 0:06
//
#pragma once
#define MaxSize 5
typedef int ElemType;
typedef struct
{
ElemType elem[MaxSize];
int top; //栈指针
}SqStack;
void InitStack(SqStack* &s);
void ClearStack(SqStack* &s);
int StackLength(SqStack* s);
int StackEmpty(SqStack* s);
int Push(SqStack* &s,ElemType e); //进栈
int Pop(SqStack* &s,ElemType& e); //出栈
int GetTop(SqStack* &s,ElemType& e); //取栈顶元素
void DispStack(SqStack* s);
//SqStack.cpp
#include "SqStack.h"
#include <malloc.h>
#include <stdio.h>
void InitStack( SqStack* &s )
{
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1;
}
void ClearStack( SqStack* &s )
{
free(s);
}
int StackLength( SqStack* s )
{
return s->top+1;
}
int StackEmpty( SqStack* s )
{
return s->top == -1;
}
int Push( SqStack* &s,ElemType e )
{
if ( s->top >= MaxSize -1)
{
return 0;
}
s->top ++;
s->elem[s->top] = e;
return 1;
}
int Pop( SqStack* &s,ElemType& e )
{
if ( -1 == s->top)
{
return 0;
}
s->top--;
return 1;
}
int GetTop( SqStack* &s,ElemType& e )
{
if ( s->top == -1 || s->top >= MaxSize)
{
return 0;
}
e = s->elem[s->top];
return 1;
}
void DispStack( SqStack* s )
{
if ( s->top == -1 || s->top >= MaxSize)
{
return;
}
for ( int i = s->top; i >= 0; i --)
{
printf("%d,",s->elem[i]);
}
printf("\n");
}
main.cpp
#include "SqStack.h"
int main()
{
SqStack*s;
InitStack(s);
Push(s,1);
DispStack(s);
Push(s,2);
DispStack(s);
Push(s,3);
DispStack(s);
Push(s,4);
DispStack(s);
ElemType e;
Pop(s,e);
DispStack(s);
return 0;
}