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

这是一个C++实现的数组栈程序,包括初始化、清空、判断是否为空、获取栈顶元素、压栈、弹栈、获取长度和遍历栈等功能。通过示例展示了如何使用该栈操作整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 ============================================================================
 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 10
typedef 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值