顺序表示
#include <stdlib.h>
#include <iostream>
using namespace std;
enum { MAXNUM = 20 }; /* 栈中最大元素个数,应根据需要定义 */
typedef int DataType; /* 栈中元素类型,应根据需要定义 */
struct SeqStack { /* 顺序栈类型定义 */
int t; /* 栈顶位置指示 */
DataType s[MAXNUM];
};
typedef struct SeqStack SeqSack, *PSeqStack; /* 顺序栈类型和指针类型 */
/*创建一个空栈;为栈结构申请空间,并将栈顶变量赋值为-1*/
PSeqStack createEmptyStack_seq(void) {
PSeqStack pastack = (PSeqStack)malloc(sizeof(struct SeqStack));
if (pastack == NULL)
printf("Out of space!! \n");
else
pastack->t = -1;
return pastack;
}
/*判断pastack所指的栈是否为空栈,当pastack所指的栈为空栈时,则返回1,否则返回0*/
int isEmptyStack_seq(PSeqStack pastack) {
return pastack->t == -1;
}
/* 在栈中压入一元素x */
void push_seq(PSeqStack pastack, DataType x) {
if (pastack->t >= MAXNUM - 1)
printf("Stack Overflow! \n");
else {
pastack->t++;
pastack->s[pastack->t] = x;
}
}
/* 删除栈顶元素 */
void pop_seq(PSeqStack pastack) {
if (pastack->t == -1)
printf("Underflow!\n");
else
pastack->t--;
}
/* 当pastack所指的栈不为空栈时,求栈顶元素的值 */
DataType top_seq(PSeqStack pastack) {
return pastack->s[pastack->t];
}
int main()
{
PSeqStack st;
st = createEmptyStack_seq();
cout << isEmptyStack_seq(st) << endl;
push_seq(st, 1);
push_seq(st, 2);
push_seq(st, 3);
cout << top_seq(st) << endl;
pop_seq(st);
cout << top_seq(st) << endl;
cout << isEmptyStack_seq(st) << endl;
}
链接表示
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int DataType;
struct Node; /* 单链表结点 */
typedef struct Node *PNode; /* 指向结点的指针类型 */
struct Node { /* 单链表结点结构 */
DataType info;
PNode link;
};
struct LinkStack { /* 链接栈类型定义 */
PNode top; /* 指向栈顶结点 */
};
typedef struct LinkStack *PLinkStack; /* 链接栈类型的指针类型 */
/*申请链栈结构空间,创建一空链接栈,返回指向空链接栈的指针*/
PLinkStack createEmptyStack_link(void) {
PLinkStack plstack;
plstack = (PLinkStack)malloc(sizeof(struct LinkStack));
if (plstack != NULL)
plstack->top = NULL;
else
printf("Out of space! \n");
return plstack;
}
/*判单链形式栈是否为空栈*/
int isEmptyStack_link(PLinkStack plstack) {
return plstack->top == NULL;
}
/* 在栈中压入一元素x */
void push_link(PLinkStack plstack, DataType x) {
PNode p;
p = (PNode)malloc(sizeof(struct Node));
if (p == NULL)
printf("Out of space!\n");
else {
p->info = x;
p->link = plstack->top;
plstack->top = p;
}
}
/*出栈*/
void pop_link(PLinkStack plstack) {
if (isEmptyStack_link(plstack))
printf("Empty stack pop.\n");
else {
PNode p = plstack->top;
plstack->top = plstack->top->link;
free(p);
}
}
/* 对非空栈求栈顶元素 */
DataType top_link(PLinkStack plstack) {
return plstack->top->info;
}
int main()
{
PLinkStack st;
st = createEmptyStack_link();
cout << isEmptyStack_link(st) << endl;
push_link(st, 1);
push_link(st, 2);
push_link(st, 3);
cout << top_link(st) << endl;
pop_link(st);
cout << top_link(st) << endl;
cout << isEmptyStack_link(st) << endl;
}