堆栈之数组实现

#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;
}
原文地址:https://www.cnblogs.com/kbyd/p/3991595.html