两个顺序栈共享空间基本实现(C++)

这一个示例就是在顺序栈的基础上加上了一些条件判断,使得两个相同数据类型的栈能够共用一个空间。节省内存的消耗。试验代码和函数功能如下:

template<typename T>
class sqStack 
{
private:
	T data[MAXSIZE];
	int top1;
	int top2;
public:
	sqStack();   //默认构造函数;
	T GetTop(int c) const;   //得到栈c的栈顶元素;
	bool Push(const T &e, int c);  //将e压入第c号栈;
	bool Pop(int c);   //将第c号栈的栈顶元素弹出;
	bool isEmpty(int c) const; //判断第c个栈是否为空;
	bool isFull() const;  //判断内存空间有没有占满;
	void ClearStack(int c);   //清楚第c个栈;
};

共享空间的头文件

#pragma once
#ifndef STACK_H_
#define STACK_H_

#define MAXSIZE 1000

template<typename T>
class sqStack 
{
private:
	T data[MAXSIZE];
	int top1;
	int top2;
public:
	sqStack();
	T GetTop(int c) const;
	bool Push(const T &e, int c);
	bool Pop(int c);
	bool isEmpty(int c) const;
	bool isFull() const;
	void ClearStack(int c);
};

template<typename T>
sqStack<T>::sqStack() 
{
	top1 = -1;
	top2 = MAXSIZE;
}

template<typename T>
T sqStack<T>::GetTop(int c) const
{
	if (isEmpty(c)) {
		cout << "The stack is empty!\n";
		exit(EXIT_FAILURE);
	}
	else {
		if (c == 1)
			return data[top1];
		else if (c == 2)
			return data[top2];
	}
}

template<typename T>
bool sqStack<T>::Push(const T &e, int c)
{
	if (isFull())
		return false;
	else {
		if (c == 1) {
			top1 += 1;
			data[top1] = e;
		}
		else if (c == 2) {
			top2 -= 1;
			data[top2] = e;
		}
	}
}

template<typename T>
bool sqStack<T>::Pop(int c)
{
	if (isEmpty(c))
		return false;
	else {
		if (c == 1)
			top1 -= 1;
		else if (c == 2)
			top2 += 1;
	}
	return true;
}

template<typename T>
bool sqStack<T>::isEmpty(int c) const
{
	if(c==1)
		return (top1 == -1);
	if (c == 2)
		return (top2 == MAXSIZE);
}

template<typename T>
bool sqStack<T>::isFull() const
{
	return (top1 + 1 == top2);
}

template<typename T>
void sqStack<T>::ClearStack(int c)
{
	if (c == 1)
		top1 = -1;
	else if (c == 2)
		top2 = MAXSIZE;
}

#endif

共享空间的示例用法

#include<iostream>
#include<string>
#include"stack.h"

using namespace std;

void main()
{
	sqStack<string> book;
	book.Push("BOOK THIEF",1);
	book.Push("KITE RUNNER",2);
	book.Push("THE OLD MAN",1);
	cout << book.GetTop(1) << endl;
	cout << book.GetTop(2) << endl;
	book.Pop(1);
	cout << book.GetTop(1) << endl;
	book.ClearStack(1);
	cout << book.GetTop(1) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值