本文主要是介绍数据结构-栈的动态顺序存储表示-初始化压栈弹栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
由于没有设置index参数,所以该code不能随时的输出,然后再继续进行push和pop,因为一次输出栈,就把top压到了bottom,可以通过增加index,进行恢复。还有一点要注意,栈顶top,存储的是垃圾值,因为是top++操作,可以通过++top进行改正。
#include<iostream>
#include<stdlib.h>
#define STACK_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
using namespace std;typedef struct sqstack
{int *bottom;int *top;int stacksize;
}SqStack;SqStack *init_stack()
{SqStack *s;s=(SqStack*)malloc(sizeof(SqStack));s->bottom=(int*)malloc(STACK_SIZE*sizeof(int));if(!s->bottom) {return NULL;}s->top=s->bottom;s->stacksize=STACK_SIZE;return s;
}int insert_stack(SqStack *s,int num)
{if(s->top-s->bottom+1>=s->stacksize){int *prt;prt=(int*)realloc(s->bottom,(STACKINCREMENT+s->stacksize)*sizeof(int));if(!prt) return ERROR;s->bottom=prt;s->top=s->bottom+s->stacksize;s->stacksize+=STACKINCREMENT;}*s->top=num;s->top++;return OK;
}int delete_stack(SqStack *s)
{int num;if(s->top==s->bottom) return ERROR;s->top--;num=*s->top;return num;
}void show_stack(SqStack *s)
{SqStack *ns;ns=s;ns->top--;cout<<"自顶向下输出栈"<<endl;while(ns->top!=ns->bottom){cout<<*ns->top<<" ";ns->top--;}cout<<*ns->bottom<<endl;
}int main()
{SqStack *S;if(S=init_stack()){cout<<"初始化成功"<<endl;}else cout<<"初始化失败"<<endl;while(1){int choose;cout<<"插入输入1,删除输入2,输出栈输入3:";cin>>choose;if(choose==1){cout<<"输入插入的数字:";int num;cin>>num;if(insert_stack(S,num)){cout<<"插入成功"<<endl; }else {cout<<"插入失败"<<endl;}}else if(choose==2) {int num;if(num=delete_stack(S)){cout<<"删除的元素为:"<<num<<endl;} else {cout<<"栈顶元素删除失败"<<endl; }}else {show_stack(S);}}return 0;
}
这篇关于数据结构-栈的动态顺序存储表示-初始化压栈弹栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!