数据结构-栈的顺序存储结构(C++实现)
1、声明栈的结构体
结构体内声明一个data用来存放栈数据; top用来指向栈顶;
typedef int ElemType; typedef struct{ ElemType data[MAXSIZE]; int top; }SqStack;
2、初始化栈顶
因为栈是从0开始存储的,所有一开始最好将指针top指向-1
void Length(SqStack *S){ S->top = -1; }
3、添加元素至栈顶
因为我们先将栈的指针指向了-1,所以我们这应该先top++,再将元素存入栈内
int Push(SqStack *s , ElemType e){ if(s -> top == MAXSIZE -1){ //栈满 return ERROR; } s->top++; s->data[s->top] = e; return OK; }
4、删除栈顶元素
删除元素的同时将赋值给e返回
int Pop(SqStack * S , ElemType *e){ if(S->top == -1){ return ERROR; } *e = S->data[S->top]; S->top--; return OK; }
5、显示栈
应该会有更好的方法,这里我用了一个笨方法,直接使用了for循环
void show(SqStack *S){ for(int i = 0;i <= S->top;i++) { cout << S->data[i] << endl; } }
整段代码
#include <iostream> using namespace std; #define MAXSIZE 10 #define ERROR 0 #define OK 1 typedef int ElemType; typedef struct{ ElemType data[MAXSIZE]; int top; }SqStack; void Length(SqStack *S){ S->top = -1; } int Push(SqStack *s , ElemType e){ if(s -> top == MAXSIZE -1){ //栈满 return ERROR; } s->top++; s->data[s->top] = e; return OK; } void show(SqStack *S){ for(int i = 0;i <= S->top;i++) { cout << S->data[i] << endl; } } int Pop(SqStack * S , ElemType *e){ if(S->top == -1){ return ERROR; } *e = S->data[S->top]; S->top--; return OK; } int main(){ SqStack S; Length(&S); while(-1) { cout << "1---往栈顶添加元素" << endl; cout << "2---显示栈元素" << endl; cout << "3---删除栈顶元素" << endl; int i, e ,w; cin >> i; switch (i) { case 1: cout << "请问你要加入的元素" << endl; cin >> e; Push(&S, e); break; case 2: show(&S); break; case 3: Pop(&S , &e); cout << "你清除了" << e << "这个元素" << endl; break; } } }
下一篇:
bat命令快捷修改ip地址