首页 > 代码库 > 堆栈之数组实现
堆栈之数组实现
#include<iostream>using namespace std;struct Stack{ int maxCnt; int* elements; int top,bottom;};Stack* createStack(int max=100){ Stack* stack = (Stack*)malloc(sizeof(Stack)); stack->top=0; stack->bottom=0; stack->maxCnt=max; stack->elements = new int[ stack->maxCnt]; return stack;}bool push(Stack* stack,int value){ if(stack->top>=stack->maxCnt) return 0; stack->elements[stack->top++]=value; return 1;}bool isEmpty(Stack* stack){ return stack->top<=0;}bool pop(Stack* stack,int* ans){ if(isEmpty(stack)) return 0; *ans = stack->elements[--stack->top]; return 1;}bool top(Stack* stack,int* ans){ if(isEmpty(stack)) return 0; *ans = stack->elements[stack->top-1]; return 1;}void clearStack(Stack* stack){ int x; while(!isEmpty(stack)) { pop(stack,&x); }}void outPut(Stack* stack){ int x; while(!isEmpty(stack)) { pop(stack,&x); cout<<x<<" "; } cout<<endl;}void main(){ int len=12; Stack* st = createStack(); int v; for(int i=0;i<len;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; outPut(st); clearStack(st); for(int i=0;i<5;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; outPut(st); for(int i=0;i<5;i++) { v = rand() % 100; cout<<v<<" "; push(st,v); } cout<<endl; //outPut(st); pop(st,&v); cout<<v<<endl; ///outPut(st); top(st,&v); cout<<v<<endl; outPut(st); cin>>len;}
堆栈之数组实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。