一,顺序栈的实现及基本操作
#include<stdio.h>
typedef int ElemType;
#define MaxSize 20
typedef struct { //操作受限的顺序表,多一个队头指针
ElemType data[MaxSize];
int top;
}SqStack;
//初始化
void initSqStack(SqStack& S) {
S.top = -1;
}
//判断栈是否为空
bool IsFull(SqStack S) {
if (S.top == -1)
return true;
else
return false;
}
//进栈
bool Push(SqStack& S, ElemType x) {
if (S.top == MaxSize - 1)
return false;
S.data[++S.top] = x;
return true;
}
//出栈
bool Pop(SqStack& S, ElemType& x) {
if (S.top == -1)
return false;
x = S.data[S.top--];
return true;
}
//读取栈顶元素
bool GetTop(SqStack& S, ElemType& x) {
if (S.top == -1)
return false;
x = S.data[S.top];
return false;
}
//打印栈的所有元素
void PrintfSqStack(SqStack S) {
printf("栈的元素为:\n");
while (S.top != -1) {
printf("%d\n", S.data[S.top--]);
}
}
//当top指向0表示栈为空时,top==MaxSize表表示栈满
//进栈代码为:S.data[S.top++] = x;
//出栈代码为:x = S.data[--S.top]
int main() {
SqStack S;
int e = 0;
initSqStack(S);
PrintfSqStack(S);
Push(S, 1);
Push(S, 2);
Push(S, 3);
Push(S, 4);
Pop(S, e);
printf("e为;%d\n", e);
PrintfSqStack(S);
return 0;
}
2.链栈的实现及基本操作
#include<stdio.h>
#include<malloc.h>
typedef int Elemtype;
typedef struct Stacknode {
Elemtype data;
struct Stacknode* next;
}*Linkstack;
//初始化链栈
void initStack(Linkstack &S) {
S = (Linkstack)malloc(sizeof(Stacknode));
S->next = NULL;
}
//进栈 使用头插法插入结点,正好满足栈先进后出的性质
void Push(Linkstack& S, Elemtype e) {
Stacknode* s = (Stacknode*)malloc(sizeof(Stacknode));
s->data = e;
s->next = S->next;
S->next = s;
}
//出栈
bool Pop(Linkstack& S, Elemtype& e) {
if (S->next == NULL)
return false;
Stacknode* p = S->next;
S->next = p->next;
e = p->data;
free(p);
return true;
}
//读取栈顶元素
bool GetTop(Linkstack& S, Elemtype& e) {
if (S->next == NULL)
return false;
e = S->next->data;
return true;
}
//打印栈
void PrintfStack(Linkstack S) {
printf("栈为:\n");
Stacknode* p = S->next;
while (p != NULL) {
printf("%d\n", p->data);
p = p->next;
}
}
int main()
{
int x = 0;
Linkstack S;
initStack(S);
Push(S, 3);
Push(S, 2);
Push(S, 1);
PrintfStack(S);
Pop(S, x);
PrintfStack(S);
printf("x为:%d\n", x);
GetTop(S, x);
PrintfStack(S);
printf("x为:%d\n", x);
return 0;
}