码迷,mamicode.com
首页 > 编程语言 > 详细

[c++]栈模板的实现

时间:2015-07-15 11:13:28      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:栈模板

 头文件: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;
}
技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

[c++]栈模板的实现

标签:栈模板

原文地址:http://blog.csdn.net/zongyinhu/article/details/46888893

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!