栈
此篇只是一个简单的栈,没有考虑安全性问题,例如:如何解决内存不足问题;如何在多进程下,保证线程安全问题。
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
template<typename Type>
class SeqStack
{
private:
Type *data;
size_t maxsize;
int pos;//栈顶得一个整形量
private:
bool IncSize()//增容函数
{
Size_t oldlen = size();
size_t newlen = oldlen*2;
Type* newdata = (Type*)malloc(sizeof(Type)*newlen);
if(newdata == NULL)
{
//若malloc申请空间失败,os//如果失败,说明系统内存不足
return false;
}
for(int i = 0; i < oldlen; i++)
{
new(&newdata[i]) Type(data[i]);
}
for(int i = 0; i < oldlen; i++)
{
(&data[i])->~Type();
}
free(data);
data = newdata;
maxsize = newlen;
return true;
}
public:
SeqStack(int sz = 100):data(NULL),maxsize(sz),pos(-1)//构造函数
{
//data = new Type[maxsize];容器里不能拿new开辟空间//new会申请资源并调动构造函数,会耗尽资源
data = (Type*)malloc(sizeof(Type)*maxsize);
data = new Type[maxsize];
}
SeqStack(const SeqStack &seq)//拷贝构造函数//深拷贝
:data(NULL),maxsize(seq.maxsize),pos(seq.pos)
{
if(seq.data != NULL)
{
data = (Type*)malloc(sizeof(Type)*maxsize);
if(data == NULL)
exit(EXIT_FAILURE);
for(int i = 0; i < pos; i++)
{
new(&data[i]) Type(seq.data[i]);
}
}
}
SeqStack & operator=(const SeqStack &seq)
{
if(this != &seq)
{
for(int i = 0; i < pos; i++)
{
(&data[i])->~Type();
}
free(data);
maxsize = seq.maxsize;
pos = seq.pos;
data = (Type*)malloc(sizeof(Type)*maxsize);
if(data == NULL)
exit(EXIT_FAILURE);
for(int i = 0; i < pos; i++)
{
new(&data[i]) Type(seq.data[i]);
}
}
return *this;
}
void push(const Type &x)//入栈//空间不够的话,得扩容
{
if(full() && !IncSize())
{
exit(EXIT_FAILURE);
}
new(&data[++pos]) Type(x);
}
void pop()
{
(&data[pos])->~Type();
--pos;
}
Type & top()
{
return data[pos];
}
const Type &top() const
{
return data[pos];
}
bool empty() const
{
return size() == 0;
}
bool full() const
{
return size() == capacity();
}
size_t size() const//获得对象个数
{
return pos+1;
}
size_t capacity() const
{
return maxsize;
}
~SeqStack()
{
for(int i = 0; i <= top; i++)
{
(&data[i])->~Type();
}
free(data);
data = NULL;
maxsize = 0;
pos = -1;
}
};
int main()
{
SeqStack<int> ist;
SeqStack<int> is;
ist = is;
while(!ist.empty())
{
int x = ist.top();
ist.pop();
cout<<x<<endl;
}
return 0;
}
}
}