简单数据结构之数组栈(C++实现)

来源:互联网 发布:超级淘宝txt全集下载 编辑:程序博客网 时间:2024/05/19 17:58
/* ============================================================================ Name        : stack_array.cpp Author      : ntsk13 beijiwei@qq.com Version     : Copyright   : GPL Description : stack array study, complement by C++ Date        : 2015.06.17 ============================================================================ */#include <iostream>using namespace std;#define STACK_CAPACITY 10typedef struct {int data;}Elem_t;class  stack {public:Elem_t array[STACK_CAPACITY];int top;int capacity;int cur_len;void init();void clear();bool is_empty();Elem_t get_top_elem();bool push(Elem_t e);bool pop(Elem_t &e);int get_len();void traverse();};int main(void) {stack S;Elem_t zero,one,two,three,four,five,six;zero.data=0;one.data=1;two.data=2;three.data=3;four.data=4;S.init();cout<<"S is empty ? "<<( (S.is_empty()) ?"Yes":"No")<<endl;S.pop(six);S.push(zero);S.push(one);S.push(two);S.push(three);S.push(four);cout<<"S is empty ? "<< (S.is_empty() ?"Yes":"No")<<endl;five=S.get_top_elem();S.traverse();cout<<"len is "<<S.get_len()<<endl;cout<<"============================================="<<endl;S.pop(six);S.pop(five);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);S.push(four);cout<<"len is "<<S.get_len()<<endl;S.traverse();return 0;}void stack::init(){capacity=STACK_CAPACITY;cur_len=0;top=-1;}void stack::clear(){cur_len=0;top=-1;}bool stack::is_empty(){return (top==-1)?true:false;}Elem_t stack::get_top_elem(){return array[top];}bool stack::push(Elem_t e){if( top==capacity-1){cout<<"It is full, can not push !!!"<<endl;return false;}array[top+1]=e;top++;cur_len++;return true;}bool stack::pop( Elem_t & e){int tmp=top;if( is_empty() ){cout<<"It is empty, can not pop !!!"<<endl;return false;}top--;cur_len--;e=array[tmp];return true;}int stack::get_len(){return cur_len;}void stack::traverse(){int t=top;for(int i=0;i<cur_len;i++)cout<<"The "<<i<<"th elem is "<<(array[t--]).data<<endl;}

0 0
原创粉丝点击