1.先复习两个C++的基础知识
-
模板类的复制构造函数的返回值给出类型,即<type>,如下所示:
stack<type>&operator= (const stack<type> &otherStack);
注意,在operator与等号之间不要加上空格,因为“operator=”这个整体是函数名;
-
当new一个模板类的对象时,需要在类后面用尖括号指定类型,如:
node<type>*temp = new node<type>;
其实上述两点基础知识只要记住,当我们需要用模板类时,要判定此处需要的是不是一个对象,如果是则一定要加上尖括号给出虚拟的类型或者实在的类型。
2.实现说明:
昨天用数组实现了栈。相比用数组实现的栈,用链表实现的栈不会出现栈溢出的现象,当然如果内存耗尽也是会出现栈溢出的现象的。
虽然我们不需要考虑栈溢出的问题,但是一定要考虑栈是否为空的情况,这点是设计栈的过程中很容易出错误的。
3.实现代码:
#include <iostream>
using namespace std;
template <class type>
class node
{
public:
type info;
node *link;
};
template <class type>
class stack
{
public:
stack();
stack(const stack<type> &otherStack);
stack<type>& operator= (const stack<type> &otherStack);
void print();
void push(const type x);
type getTop();
type pop();
bool isEmpty();
node<type>* copy(const stack<type> &otherStack);
~stack();
private:
node<type> *top;
};
template <class type>
stack<type>::stack()
{
top = NULL;
}
template <class type>
stack<type>::stack(const stack<type> &otherStack)
{
top = copy(otherStack);
}
template <class type>
stack<type>& stack<type>::operator= (const stack<type> &otherStack)
{
stack<type> temp = new stack;
temp->top = otherStack.copy();
return *temp;
}
template <class type>
bool stack<type>::isEmpty()
{
if( NULL == top) return true;
else return false;
}
template <class type>
void stack<type>::print()
{
node<type> *temp = top;
while(NULL != temp)
{
cout << temp->info;
cout << endl;
temp = temp->link;
}
}
template <class type>
type stack<type>::getTop()
{
if(false == isEmpty()) return top->info;
else return -1;
}
template <class type>
type stack<type>::pop()
{
if(false == isEmpty())
{
type temp = top->info;
top = top->link;
return temp;
}else return -1;
}
template <class type>
void stack<type>::push(const type x)
{
node <type> *temp = new node<type>;
temp->info = x;
temp->link = top;
top = temp;
}
template <class type>
node<type>* stack<type>::copy(const stack<type> &otherStack)
{
top = NULL;
node<type> *temp = otherStack.top;
node <type> *temp2 = NULL;
while(NULL != temp)
{
temp2 = new node<type>;
temp2->info = temp->info;
temp2->link = top;
top = temp2;
temp = temp->link;
}
return top;
}
template <class type>
stack<type>::~stack()
{
node<type> *temp = top;
while(NULL != temp)
{
top = top->link;
delete temp;
temp = top;
}
}
int main(int argc, char **arg)
{
stack<int> s;
s.print();
s.push(10);
s.print();
stack<int> t = s;
t.print();
t.push(1);
t.push(12);
cout << t.getTop() << endl;
t.pop();
cout << t.getTop() << endl;
return 0;
}
4.总结:
抓住栈的特点才是设计链表栈的最根本的指导,而C++的语言特点也是要十分关注的,C++就是用来设计栈的工具,古语“公欲善其事,必先利其器”。