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