/*
============================================================================
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;
}简单数据结构之 vector 栈(C++ vector 实现)
最新推荐文章于 2025-09-04 11:13:50 发布
本文通过一个简单的C++程序展示了如何使用vector实现一个栈数据结构,包括初始化、清空、判断栈是否为空、获取栈顶元素、压栈、弹栈和遍历栈等操作。程序中定义了一个名为stack的类,使用vector动态存储数据,并提供相应的成员函数进行栈的操作。

3652

被折叠的 条评论
为什么被折叠?



