手写过单链表的类模板后,链栈的类模板写起来就很轻松了
这里要注意的地方是:链栈类的“=”重载函数的实现,不能直接用Push();
#include<iostream>
#include<cassert>
using namespace std;
//20190928
//结点类
template<class T>
class StackNode {
public:
StackNode *next;
T data;
StackNode(T x,StackNode<T>*p=NULL):data(x),next(p){}
~StackNode() {}
};
//链栈类
template<class T>
class LinkedStack {
private:
StackNode<T>*top;
public:
LinkedStack() :top(NULL) {}
~LinkedStack();
void Push(const T&x);
void Pop();
const T& getTop()const;
bool isEmpty()const;
void clear();
int getSize();
void output();
LinkedStack<T>&operator=(const LinkedStack<T>&s);
};
template<class T>
void LinkedStack<T>::clear()
{
StackNode<T>*temp;
while (top != NULL)
{
temp = top->next;
delete top;
top = temp;
}
}
template<class T>
LinkedStack<T>::~LinkedStack()
{
clear();
}
template<class T>
bool LinkedStack<T>::isEmpty()const
{
if (top == NULL)
return true;
return false;
}
template<class T>
void LinkedStack<T>::Push(const T & data) {
//将元素data压入栈顶
StackNode<T> *newStackNode = new StackNode<T>(data,NULL);
assert(newStackNode != NULL); //内存分配错误的中断处理
newStackNode->next = top;
top = newStackNode;
}
template<class T>
void LinkedStack<T>::Pop() {
//将栈顶元素弹出栈
assert(!isEmpty());//如果栈为空,则报错
StackNode<T>*temp;
temp = top->next;
delete top;
top = temp;
}
template<class T>
const T& LinkedStack<T>::getTop()const
{
assert(!isEmpty());//如果栈为空,则报错
return top->data;
}
template<class T>
int LinkedStack<T>::getSize()
{
int size = 0;
StackNode<T>*p = top;//p指针用来遍历
while (p != NULL)
{
size++;
p = p->next;
}
return size;
}
template<class T>
void LinkedStack<T>::output()
{
StackNode<T>*p = top;//p指针用来遍历
while (p != NULL)
{
cout <<p->data << " ";
p = p->next;
}
cout << endl;
}
template<class T>
LinkedStack<T>& LinkedStack<T>::operator=(const LinkedStack<T>&s)
{
clear();
top = new StackNode<T>(s.top->data,NULL);
StackNode<T>*temp_old = s.top->next;//temp_old遍历栈s
StackNode<T>*temp_new_curr;
StackNode<T>*temp_new_prev=top;
while (temp_old != NULL)
{ //注意:这里不能用Push();
StackNode<T>*temp_new_curr = new StackNode<T>(temp_old->data,NULL);
temp_new_prev->next = temp_new_curr;
temp_new_prev = temp_new_curr;
temp_old = temp_old->next;
}
return *this;
}
int main() {
LinkedStack<int>s1;
cout << "initial size:" << s1.getSize() << endl;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
s1.output();
cout << "current size:" << s1.getSize()<<endl;
cout << endl;
s1.Pop();
s1.Pop();
s1.Pop();
s1.output();
cout << "current size:" << s1.getSize() << endl;
cout << "current top data:" << s1.getTop() << endl;
cout << endl;
LinkedStack<int>s2;
s2 = s1;
cout <<"s2 output:" << endl;
s2.output();
cout << endl;
s1.clear();
cout << "After cleared size:" << s1.getSize() << endl;
system("pause");
return 0;
}
测试结果: