上一篇博客介紹瞭如何使用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、測試結果爲: