栈的基本操作包括了:入栈、出栈、判断栈是否为空、初始化等。
顺序栈的实现:
利用顺序表实现栈的基本操作:
#include<bits/stdc++.h>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
#define line cout<<"----------"<<endl;
#define MAXSIZE 6
#define SElemType int
#define Status bool
#define OK 1
#define ERROR 0
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
SqStack st;
Status InitStack(SqStack &S){
S.base = new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
Status Push(SqStack &S, SElemType e){
if(S.top - S.base == S.stacksize)
return ERROR;
*S.top++ = e;
return OK;
}
Status Pop(SqStack &S, SElemType &e){
if(S.top == S.base) return ERROR;
e = *--S.top;
return OK;
}
SElemType GetTop(SqStack &S){
if(S.top != S.base)
return *(S.top - 1);
}
Status IsEmpty(SqStack &S){
if(st.base == st.top) return true;
else return false;
}
int main(){
InitStack(st);
for(int i = 0; i < MAXSIZE; i++)
Push(st, i+1);
while(!IsEmpty(st)){
printf("当前栈顶元素为:%d\n", GetTop(st));
SElemType x;
Pop(st, x);
printf("当前弹出元素为:%d\n\n", x);
}
printf("当前栈为空\n");
return 0;
}
链栈的实现
利用链表实现栈的基本操作
#include<bits/stdc++.h>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
#define line cout<<"----------"<<endl;
#define MAXSIZE 6
#define SElemType int
#define Status bool
#define OK 1
#define ERROR 0
typedef struct StackNode{
SElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
StackNode *p;
LinkStack st;
Status InitStack(LinkStack &S){
S = NULL;
return OK;
}
Status Push(LinkStack &S, SElemType e){
p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S, SElemType &e){
if(S == NULL) return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
SElemType GetTop(LinkStack S){
if(S != NULL)
return S->data;
}
Status IsEmpty(LinkStack S){
if(S == NULL) return true;
else return false;
}
int main(){
InitStack(st);
for(int i = 0; i < MAXSIZE; i++)
Push(st, i+1);
while(!IsEmpty(st)){
printf("当前栈顶元素为:%d\n", GetTop(st));
SElemType x;
Pop(st, x);
printf("当前弹出元素为:%d\n\n", x);
}
printf("当前栈为空\n");
return 0;
}