码迷,mamicode.com
首页 > 其他好文 > 详细

堆栈之数组实现

时间:2014-09-24 23:17:17      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   sp   

#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;
}

 

堆栈之数组实现

标签:style   blog   color   io   os   ar   for   div   sp   

原文地址:http://www.cnblogs.com/kbyd/p/3991595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!