第十二章编程练习(4)

STACK.h

#pragma once
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack {
private:
	enum { MAX = 10 };
	Item * pitems;
	int size;//需要创建的数组大小
	int top;//数组下标
public:
	Stack(int n = MAX);
	Stack(const Stack & st);
	~Stack();
	bool isfull()const;
	bool isempty()const;
	bool push(const Item & item);
	bool pop(Item & item);
	Stack & operator=(const Stack & st);
};
#endif

STACK.cpp

#include "STACK.h"
#include <iostream>
Stack::Stack(int n)
{
	pitems = new Item[n];
	pitems[0] = 0;
	size = n;
	top = 0;
}

Stack::Stack(const Stack & st)
{
	size = st.size;
	pitems = new Item[size];
	for (int i = 0; i < size; i++)
		*(pitems+i) = *(st.pitems+i);
	top = st.top;
}

Stack::~Stack()
{
	delete[]pitems;
}

bool Stack::isfull() const
{
	return top==size;
}

bool Stack::isempty() const
{
	return top==0;
}

bool Stack::push(const Item & item)
{
	if (top < size)
	{
		*(pitems + (top++)) = item;
		return true;
	}
	else
		return false;
}

bool Stack::pop(Item & item)
{
	if (top > 0)
	{
		item = *(pitems + (--top));
		return true;
	}
	else
		return false;
}

Stack & Stack::operator=(const Stack & st)
{
	size = st.size;
	for (int i = 0; i < size; i++)
		*(pitems + i) = *(st.pitems + i);
	top = st.top;
	return *this;
}


main.cpp

#include <iostream>
#include "STACK.h"
#include <cstdlib>
#include <cctype>
using namespace std;
int main()
{
	Stack st;
	char ch;
	unsigned long po;
	cout << "Please enter A to add a purchase order,\n"
		<< "P to process a PO, or Q to quit.\n";
	while (cin >> ch&&toupper(ch) != 'Q')
	{
		while (cin.get() != '\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 already full\n";
			else
				st.push(po);
			break;
		case'P':
		case'p':if (st.isempty())
			cout << "stack already empty\n";
				else {
					st.pop(po);
					cout << "PO #" << po << " popped\n";
				}
				break;
		}
		cout << "Please enter A to add a purchase order,\n"
			<< "P to process a PO, or Q to quit.\n";
	}
	Stack st1;
	st1 = st;
	cout << "process a PO:\n";
	st1.pop(po);
	cout << "PO #" << po << " popped\n";
	Stack st2(st);
	cout << "PO #" << po << " popped\n";
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值