简介及代码
首先创建一个结构体模板,即一个链表节点,作为栈的单元。
template <class T>
struct LinkedList{
T val;
struct LinkedList<T>* next;
// LinkedList(T v):val(v),next(NULL){}
};
然后新建一个类,该类有两个成员,分别为栈顶指针top和栈的大小size,top永远指向链表的头部,由于栈只能操作栈顶元素,故新的节点可插入到链表的头部;该类实现了push、pop、empty、getSize四个方法,具体见代码及注释。
//模板链表栈
template <class T>
class Mystack{
public:
//Initial the stack's size equals 0.
Mystack(){
top = NULL;
size = 0;
}
//Use a new node to store data,and make the node's next point to top,then make the pointer top point to the new node.
void push(const T& node){
LinkedList<T>* t = new LinkedList<T>;
t->val = node;
t->next = top;
top = t;
++size;
}
//Make top point to the next node,and return his value.
T pop(){
LinkedList<T>* temp = top;
top = top->next;
T ret= temp->val;
delete temp;
--size;
return ret;
}
//If top is nullptr,the stack is empty.
bool empty(){
return top == NULL;
}
//Get the stack's size.
int getSize(){
return size;
}
private:
LinkedList<T>* top;
int size;
};
测试代码
使用整形和字符串测试正确性以及通用性。
#include <iostream>
#include <string>
int main(){
Mystack<int> s;
s.push(1);
s.push(2);
s.push(4);
while(!s.empty()){
std::cout << "value:" << s.pop() << std::endl;
std::cout << "size:" << s.getSize() << std::endl;
}
Mystack<std::string> str;
str.push("Zhang si");
str.push("Li san");
while(!str.empty()){
std::cout << str.pop() << std::endl;
}
return 0;
}
测试结果
后记
第一篇博客,水平和语言表达能力有限,勿喷。