加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
chap05_02.cpp 1.90 KB
一键复制 编辑 原始数据 按行查看 历史
#include <iostream>
using namespace std;
class CStack
{
private:
char *s; //栈的内容保存在s中
int tp; //栈顶指示器,栈空为-1
int size;
public:
CStack(int initSize = 5);
CStack(const CStack &scopy);
CStack operator=(const CStack &scopy);
~CStack();
bool isEmpty();
bool isFull();
void push(char c);
char pop();
char top();
};
CStack CStack::operator=(const CStack &scopy)
{
if (this == &scopy) return *this;
if(s!=NULL) free(s);
size = scopy.size;
tp = scopy.tp;
s = NULL;
if (size!=0)
{
s = new char[size];
for (int i=0; i<=tp; i++)
s[i] = scopy.s[i];
}
return *this;
}
bool CStack::isEmpty()
{
return (tp==-1);
}
bool CStack::isFull()
{
return (tp==(size-1));
}
void CStack::push(char c)
{
if (isFull())
{
char *p = new char[2*size];
for (int i=0; i<size; i++)
p[i] = s[i];
delete []s;
s = p;
size = 2*size;
}
tp++;
s[tp] = c;
}
char CStack::pop()
{
int oldtp = tp;
tp--;
return s[oldtp];
}
char CStack::top()
{
return s[tp];
}
CStack::CStack(int initSize)
{
tp = -1;
size = initSize;
s = new char[size];
}
CStack::CStack(const CStack &scopy)
{
tp = scopy.tp;
size = scopy.size;
if (size!=0)
{
s = new char [size];
for (int i=0; i<=tp; i++)
s[i] = scopy.s[i];
}
}
CStack::~CStack()
{
if (s!=NULL)
{
delete []s;
s = NULL;
}
}
int main()
{
CStack s;
for(int i=0; i<7; i++) s.push('a'+i);
CStack sCopy;
sCopy = s;
while(!s.isEmpty()) cout << s.pop();
cout << endl;
for(int i=0; i<7; i++) s.push('1'+i);
while(!sCopy.isEmpty()) cout<<sCopy.pop();
cout<<endl;
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化