[c++]栈模板的实现

 头文件:StackTP.h

#ifndef __STACKTP_H__
#define __STACKTP_H__

template<typename T>
class Stack
{
public:
	Stack();
	bool IsFull();
	bool IsEmpty();
	bool Push(const T &x);
	bool Pop(T &x);
	int Lenth();
	void Show();
private:
	enum{MAX = 10};//枚举类型是常数,类似#define MAX 10
	T item[MAX];
	int top;
};

template<typename T>
Stack<T>::Stack()
{
	top = 0;
}
template<typename T>
bool Stack<T>::IsFull()
{
	return top == MAX;
}
template<typename T>
bool Stack<T>::IsEmpty()
{
	return top == 0;
}
template<typename T>
bool Stack<T>::Push(const T &x)
{
	if (IsFull())
	{
		std::cout << "the stack is full!" << std::endl;
		return false;
	}
	item[top++] = x;
	return true;
}
template<typename T>
bool Stack<T>::Pop(T &x)
{
	if ( IsEmpty() )
	{
		std::cout << "the stack is empty!" << std::endl;
		return false;
	}
	x = item[--top];
	return true;
}
template<typename T>
int Stack<T>::Lenth()
{
	return top;
}
template<typename T>
void Stack<T>::Show()
{
	for (int i = 0; i < top; ++i)
	{
		std::cout << item[i] << " ";
	}
	cout << std::endl;
}
#endif
测试程序1:

#include"StackTP.h"
#include<iostream>
#include<stdlib.h>
using std::cout;
using std::endl;

int main()
{
	Stack<int> s;
	for (int i = 0; i < 10; ++i)
	{
		s.Push(i);
	}
	cout << s.Lenth() << endl;
	s.Show();
	int item;
	for (int i = 0; i < 9; ++i)
	{
		s.Pop(item);
	}
	s.Show();
	system("pause");
	return 0;
}


测试程序2:

//使用字符串作为购货订单ID
#include<iostream>
#include<string>
#include<ctype.h>//toupper(将字母转化为大写字母) isalpha(判断输入的是否为英文字符)
#include"StackTP.h"
using std::cin;
using std::cout;
using std::endl;

int main()
{
	Stack<std::string> st;
	char ch;
	std::string po;
	cout << "please enter A to add a purchase order" << endl;
	cout << "P to process a PO , or Q to quit" << endl;

	while (cin >> ch && toupper(ch) != 'Q')
	{
		while (cin.get() != '\n')//\n也会打入缓冲区中,此句略过\n,即如果读取的是\n 则继续读取,否则结束读取,执行下面语句
			continue;
		if (!isalpha(ch))//判断输入的字符是否为英文字符
		{
			cout << '\a';//如果输入的不是英文字符发出警告
			continue;
		}
		switch (ch)
		{
		case 'A':
		case 'a':
			cout << "enter a PO number to add:";
			cin >> po;
			if (st.IsFull())
				cout << "stack is full" << endl;
			else
				st.Push(po);
			break;
		case 'P':
		case 'p':
			if (st.IsEmpty())
				cout << "stack is empty" << endl;
			else
			{
				st.Pop(po);
				cout << "PO #" << po << "popped" << endl;
				break;
			}
		default:
			break;
		}
		cout << "please enter A to add a purchase order" << endl;
		cout << "P to process a PO , or Q to quit" << endl;
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值