c++primerplus第六版第十二章第四答案

#pragma once
typedef unsigned long Item;
#include<iostream>
class stack
{
	enum { max = 3 };
	Item *pitem;
	int size;
	int top;

public:

	stack(int n = max);
	stack(const stack&st);
	~stack();
	bool isempty()const;
	bool isfull()const;
	bool push(const Item&item);
	bool pop(Item&item);
	stack&operator=(const stack&st);
	friend std::ostream & operator<<(std::ostream &os, const stack &a);


};


```cpp
#include "stack.h"
//#include<iostream>

stack::stack(int n)
{
	pitem = new Item[n];
	int size =0;
	top = 0;


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

	}
	
	size = st.size;
	top = st.top;




}

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

}
bool stack::isfull()const
{
	return top == max;
}
bool stack::push(const Item&item)
{
	if (top == max)
	{
		std::cout << "full";
		return false;
	}
	else

	{
		pitem[top++] = item;
		return true;
	}
		



}
bool stack::pop(Item&item)
{
	if (top == 0)
	{
		std::cout << "empty";
		return false;
	}
	else
	{
		item = pitem[--top];
		return true;
	}

}
stack &stack::operator=(const stack&st)
{
	if (this == &st)
		return *this;
	delete[]pitem;
	pitem = new Item[st.size];
	size = st.size;
	top = st.top;
	for (int i = 0; i < top; i++)
	{
		pitem[i] = st.pitem[i];

	}

	return *this;




}
std::ostream & operator<<(std::ostream &os, const stack &a)
{
	
	for (int i = 0; i < a.top; i++)
	{
		os << a.pitem[i];
	}
	return os;

}

stack::~stack()
{
	delete[]pitem;
}


```cpp
#include<iostream>
#include"stack.h"
using namespace std;
int main()
{
	char ch;
	stack s1;
	unsigned long po;
	cout << "enter a ch;";
	while (cin >> ch && ch != 'q')
	{
		while (cin.get() != '\n')
			continue;
		switch (ch)
		{
		case 'a':
			if (s1.isempty())
			{
			
				cout << "empty is u";

			}
			else
			{

				s1.pop(po);
				cout << "pop is" << po;
			}
			break;
		case'b':
			if (s1.isfull())
			{
				cout << "full u cant";

			}
			else
			{
				cout << "enter a number";
				cin >> po;
				s1.push(po);
			}
			break;

			
		default:
			break;
		}


		cout << "enter a ch;";


	}
	cout << s1;
	stack st2;
	st2 = s1;
	cout << "stack2 = stack is:\n" << st2;







	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值