上一篇博客介绍了如何使用c++实现顺序栈,可以查看下面的链接:
和线性表一样,栈也存在链式存储结构,简称为:链栈;下面我们就看链栈是如何使用c++实现的(保证结果可复现):
代码块包括所示的三个部分:
1、首先是头文件部分(声明和定义链栈类):
#ifndef _LINKSTACK_H
#define _LINKSTACK_H
#include <iostream>
using namespace std;
template <class ElemType>
struct Node {
ElemType data;
Node *next;
};
template <class ElemType>
class LinkStack
{
public:
LinkStack();
virtual ~LinkStack();
void push(ElemType &e);
void pop();
bool isEmpty();
int getSize();
void display();
ElemType &getTop();
int size;
Node<ElemType> *top;
};
#endif
2、其次是函数定义部分:
#include "LinkStack.h"
template <class ElemType>
LinkStack<ElemType>::LinkStack(){
top = NULL;
this->size = 0;
}
template <class ElemType>
LinkStack<ElemType>::~LinkStack(){
}
template <class ElemType>
void LinkStack<ElemType>::push(ElemType &e) {
Node<ElemType> *newPtr = new Node<ElemType>;
newPtr->data = e;
newPtr->next = top;
top = newPtr;
this->size++;
}
template <class ElemType>
void LinkStack<ElemType>::pop() {
Node<ElemType> *p = top;
top = top->next;
delete p;
this->size--;
}
template<class ElemType>
bool LinkStack<ElemType>::isEmpty(){
if ( !top )
return true;
else
return false;
}
template <class ElemType>
int LinkStack<ElemType>::getSize() {
return this->size;
}
template <class ElemType>
void LinkStack<ElemType>::display() {
if (!top) {
cout << "stack is empty " << endl;
return;
}
Node<ElemType> *ptr = top;
while (ptr) {
cout << ptr->data << " ";
ptr = ptr->next;
}
}
template <class ElemType>
ElemType &LinkStack<ElemType>::getTop() {
return top->data;
}
3、最后是测试函数(main函数):
#include "LinkStack.h"
#include "LinkStack.cpp"
#include <iostream>
int main()
{
LinkStack<int> ls;
cout << "********************" << endl;
cout << "未插入元素的栈";
cout << "是否为空栈:" << boolalpha << ls.isEmpty() << endl;
cout << "元素数为: " << ls.getSize() << endl;
ls.display();
cout << "********************" << endl;
for (int i = 0; i < 10; ++i) {
ls.push(i);
}
cout << "插入元素后:";
cout << "是否为空栈:" << boolalpha << ls.isEmpty() << endl;
cout << "元素数为: " << ls.getSize() << endl;
cout << "栈顶元素是:" << ls.getTop() << endl;
ls.display();
cout << endl;
cout << "********************" << endl;
ls.pop();
cout << "弹出元素后的栈";
cout << "是否为空栈:" << boolalpha << ls.isEmpty() << endl;
cout << "元素数为: " << ls.getSize() << endl;
cout << "弹出后栈顶的栈顶元素是:" << ls.getTop() << endl;
ls.display();
cout << endl;
system("pause");
return 0;
}
4、测试结果为: