數據結構學習:c++實現棧的鏈式存儲結構

上一篇博客介紹瞭如何使用c++實現順序棧,可以查看下面的鏈接:

https://blog.csdn.net/weixin_42119041/article/details/102405438

和線性表一樣,棧也存在鏈式存儲結構,簡稱爲:鏈棧;下面我們就看鏈棧是如何使用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、測試結果爲:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章