要求:
- 实现大小为10,数据类型为整型的静态栈
- 实现过程结合单例模式
思路:
- 游标_pstr始终指向下一个要被填充的空间
- 数据入栈,游标_pstr加1
- 数据出栈,游标_pstr减1
示例图:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
class Stack
{
public:
static Stack * getInstance() //单例模式实现相关
{
if(nullptr==_pInstance)
{
_pInstance=new Stack();
}
return _pInstance;
}
static void destroy() //单例模式实现相关
{
if(_pInstance)
{
delete _pInstance;
}
}
void print()
{
for(int i=9;i>=0;i--)
{
cout << "data[" << i << "]= "<<_data[i] << endl;
}
}
/***元素入栈***/
void push(int data);
/***元素出栈***/
void pop();
/***读出栈顶元素***/
int top();
/***判断栈空***/
bool empty();
/***判断栈满***/
bool full();
private:
Stack()
: _pstr(0)
{
bzero(_data,sizeof(_data));
cout << "Stack()" << endl;
}
~Stack()
{
cout << "~Stack()" << endl;
}
private:
int _data[10];
int _pstr;
static Stack *_pInstance;
};
/***Stack类元素入栈实现***/
void Stack::push(int data)
{
if(_pstr<10)
{
_data[_pstr]=data;
_pstr++;
}else
{
cout << "error: Stack is full" << endl;
}
}
/***Stack类元素出栈实现***/
void Stack::pop()
{
if(_pstr>0)
{
_pstr--;
_data[_pstr]=0;
}else
{
cout << "error: Stack is empty" << endl;
}
}
/***Stack类读栈顶元素实现***/
int Stack::top()
{
if(_pstr>0)
{
return _data[_pstr-1];
}
return -1;
}
/***Stack类判断栈空***/
bool Stack::empty()
{
if(0==_pstr)
{
return true;
}else
{
return false;
}
}
/***Stack类判断栈满***/
bool Stack::full()
{
if(10==_pstr)
{
return true;
}else
{
return false;
}
}
Stack * Stack::_pInstance=nullptr;
int main() //测试
{
Stack *s1=Stack::getInstance();
s1->push(10);
s1->push(12);
s1->push(14);
cout << "top is " << s1->top() << endl;
s1->pop();
cout << "top is " << s1->top() << endl;
s1->pop();
cout << "top is " << s1->top() << endl;
s1->pop();
cout << "top is " << s1->top() << endl;
s1->pop();
for(int i=0;i<11;i++)
{
s1->push(i);
}
cout << "top is " << s1->top() << endl;
Stack::destroy();
return 0;
}
2021/1/18