stack 类实现
点击此处浏览C++官方的stack详细内容
主要功能有以下几个
函数 | 功能 |
---|---|
empty | 测试 stack 是否为空 |
pop | 从 stack 的顶部删除元素 |
push | 将元素添加到 stack 顶部 |
size | 返回 stack 中的元素数量 |
top | 返回对 stack 顶部元素的引用 |
自己实现stack类
只要清楚栈先进后出的原理就很好实现
# include<iostream>
# include<string>
using namespace std;
template<typename T> class Node
{
public:
T value;
Node* next = NULL;
};
template<typename T> class Mystack
{
private:
int length; //栈的长度
Node<T>* topNode; //栈顶结点
public:
Mystack()
{
length = 0;
topNode = NULL;
}
bool empty()
{
return length == 0;
}
void pop()
{
if(empty()) //栈已经为空,不做删除
return;
Node<T>* temp = topNode; //临时结点
topNode = topNode->next;
delete(temp);
length--;
}
void push(T val)
{
Node<T>* temp = new Node<T>();
temp->value = val;
temp->next = topNode;
topNode = temp;
length++;
}
int size()
{
return length;
}
T top()
{
return topNode->value;
}
void clear()
{
Node<T>* temp;
while(length)
{
cout<<top()<<endl;
temp = topNode;
topNode = topNode->next;
delete(temp);
length--;
}
}
};
int main() //测试
{
Mystack<string> s;
s.push("abc");
s.push("def");
s.push("ghi");
s.push("jkl");
s.push("mno");
int len = s.size();
for(int i = 0; i < len; i++)
{
cout<<s.top()<<endl;
s.pop();
}
cout<<s.empty()<<endl;
return 0;
}
运行结果:
确实是先进后出的
mno
jkl
ghi
def
abc
1