创作本文目的:记录自己的学习历程
一、C++实现链式栈类
1.代码
#include <iostream>
using namespace std;
template <typename T>
class Mystack
{
private:
typedef struct node
{
T data;
struct node *next;
}LS;
LS *ls;
public:
//构造函数
Mystack(T t)
{
ls = new LS;
ls->data = t;
ls->next = nullptr;
}
//析构函数
~Mystack()
{
delete ls;
ls=nullptr;
}
//拷贝构造函数
Mystack(const Mystack &other)
{
this->ls = new LS;
LS *q=other.ls;
while(q->next!=nullptr)
{
this->push(q->data);
q=q->next;
}
}
//判空
bool empty()
{
return (this->ls==nullptr?1:0);
}
//访问栈顶元素
T top()
{
if(this->empty())
{
cout<<"链栈为空"<<endl;
return 0;
}
return this->ls->data;
}
//栈中容纳的元素数
int size()
{
if(this->empty())
{
return 0;
}
int count=1;
LS *q=ls;
while(q->next!=nullptr)
{
count++;
q=q->next;
}
return count;
}
//向栈顶插入元素
void push(T x)
{
LS *p;
p=new LS;
p->data=x;
p->next=this->ls;
this->ls=p;
}
//删除栈顶元素
void pop()
{
LS *p;
if(this->empty())
{
cout<<"链栈为空"<<endl;
return;
}
p=this->ls;
this->ls=this->ls->next;
delete p;
}
};
int main(int argc, const char *argv[])
{
Mystack<int> s(1);
cout<<"当前栈中元素个数:"<<s.size()<<endl;
cout<<"栈顶元素:"<<s.top()<<endl;
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout<<"当前栈中元素个数:"<<s.size()<<endl;
cout<<"栈顶元素:"<<s.top()<<endl;
Mystack<int> s2(s);
cout<<"当前栈中元素个数:"<<s.size()<<endl;
cout<<"栈顶元素:"<<s.top()<<endl;
s.pop();
s.pop();
cout<<"当前栈中元素个数:"<<s.size()<<endl;
cout<<"栈顶元素:"<<s.top()<<endl;
return 0;
}