基于数组的栈 Stack类

/*--Stack.h------------------------------------------------*/
#pragma once
#include <iostream>

#ifndef STACK
#define STACK

const int STACK_CAPACITY =128;
typedef int StackElement;


class Stack
{
public:
	Stack(void);   //构造函数 
	
	bool empty() const;   //检查栈是否为空
	void push(const StackElement & value);   //通过栈顶添加一个元素来修改栈
	void display(ostream & out) const;   //显示所有的栈元素
	StackElement top() const;   //提取栈顶元素
	void pop();      //通过删除栈顶元素来修改栈
private:
	StackElement myArray[STACK_CAPACITY];
	int myTop;
};

#endif


/*--Stack.cpp-----包含Stack成员函数的实现------------------*/
#include <iostream>
using namespace std;

#include "Stack.h"

Stack::Stack(void):myTop(-1)    //初始化构造函数
{
}

bool Stack::empty() const    //判断是否为空栈
{
	return -1==myTop;
}

void Stack::push(const StackElement & value)   //将元素压入栈中
{
	if(myTop < STACK_CAPACITY -1)      //栈未满
	{
		++myTop;
		myArray[myTop] = value;
	}
	else
	{
		cerr<<"***Stack full -- can't add new value ***\n"
			"Must increase value of SACK_CAPACITY in Stack.h \n";
		exit(1);
	}
}


void Stack::display(ostream & out) const    //显示栈全部元素
{
	for(int i = myTop; i >=0; i--)
	{
		cout<<myArray[i]<<endl;
	}
}

StackElement Stack::top() const   //返回栈顶元素
{
	if(!empty())   //非空
	{
		return (myArray[myTop]);
	}
	else
	{
		cerr<<"*** Stack is empty--return garbage \n";
		return rand();    //返回一个随机数
	}
}

void Stack::pop()   //弹出栈顶元素
{
	if(!empty())   //栈非空
	{
		myTop--;
	}
	else
	{
		cerr<<"*** Stack is empty -- can't remove a value ***\n";
	}
}



/*--测试 Stack 类 ----------------------------------------*/
#include <iostream>
using namespace std;

#include "Stack.h"

int main()
{
	Stack s;
	cout<<"Stack created. Empty? "<<boolalpha<<s.empty()<<endl;
	cout<<"How many elements to add to the stack? ";
	int numItems;   
	cin>>numItems;   //指定栈中元素个数

	for(int i = 1; i <= numItems; i++)   //入栈
		s.push(i);
	cout<<"Stack contents: \n";
	s.display(cout);   //显示栈的全部元素
	cout<<"Stack empty?"<<s.empty()<<endl;

	cout<<"Top value: "<<s.top()<<endl;   

	while(!s.empty())
	{
		cout<<"Popping "<<s.top()<<endl;
		s.pop();
	}
	cout<<"Stack empty? "<<s.empty()<<endl;
	cout<<"Top value: "<<s.top()<<endl;
	cout<<"Trying to pop: "<<endl;
	s.pop();

	return 0;	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值