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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/beijiwei/article/details/46532799
/*
 ============================================================================
 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>
#include <vector>
using namespace std;

#define STACK_CAPACITY 10
typedef struct {
	int data;
}Elem_t;

class  stack {
public:
	vector<Elem_t> v;
	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 v.at(top);
}
bool stack::push(Elem_t e)
{
	if( top==capacity-1)
	{
		cout<<"It is full, can not push !!!"<<endl;
		return false;
	}
	top++;
	v.push_back(e);
	
	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=v.at(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 "<<(v[t--]).data<<endl;
}

展开阅读全文

没有更多推荐了,返回首页