數據結構學習:c++實現棧的順序存儲結構

c++實現棧的順序存儲結構的方法和實現順序線性表的操作差不多,甚至要比實現線性表還要簡單一點,因爲棧可以認爲是隻允許在表尾(棧頂)進行插入和刪除操作的線性表,只在表尾就很方便操作

話不多說,直接代碼:

首先是頭文件部分:

#pragma once
#include <iostream>
#define MAXSIZE 100
using namespace std;

template <class ElemType>
class MyStack
{
public:
	MyStack();
	virtual ~MyStack();
	bool isEmpty() const;                //判斷棧是否爲空
	bool isFull() const;                 //判斷棧是否已滿
	int getSize() const;                 //獲得棧中的元素數
	void push(ElemType &e);              //進棧操作
	void pop();                          //出棧操作
	void display();                      //打印棧(注意不能是常量函數)

	ElemType stack[MAXSIZE];
	int top;                    //棧頂指針
	int size;                   //棧中的元素數

};

然後是函數的定義:

#include "MyStack.h"

//構造函數

template <class ElemType>
MyStack<ElemType>::MyStack(){
	this->top = -1;
	this->size = 0;
}

//析構函數

template <class ElemType>
MyStack<ElemType>::~MyStack(){
}

//判斷棧空

template<class ElemType>
bool MyStack<ElemType>::isEmpty() const
{
	if (this->top == -1) {
		return true;
	}else {
		return false;
	}
}

//判斷棧滿

template<class ElemType>
bool MyStack<ElemType>::isFull() const{
	if (top >= MAXSIZE) {
		cout << "棧滿" << endl;
		return true;
	}else {
		return false;
	}
}

//獲取棧中元素數

template <class ElemType>
int MyStack<ElemType>::getSize() const {
	return this->size;
}

//進棧操作

template<class ElemType>
void MyStack<ElemType>::push(ElemType & e){
	if (top == MAXSIZE - 1) {
		cout << "棧滿,不能插入" << endl;
		return;
	}
	this->top++;
	stack[top] = e;
	this->size++;
}

//出棧操作

template <class ElemType>
void MyStack<ElemType>::pop() {
	if (this->top == -1) {
		cout << "棧空" << endl;
	}
	ElemType e;
	e = stack[this->top];
	this->top--;
	--size;
}

//打印棧

template<class ElemType>
void MyStack<ElemType>::display(){
	for (size_t i = 0; i < size; ++i) {
		cout << stack[i] << " ";
	}
	cout << endl;
}

最後是驗證部分(main函數):

#include "MyStack.h"
#include "MyStack.cpp"
#include <iostream>
using namespace std;

int main()
{
	MyStack<int> stack;
	cout << "**********************" << endl;
	cout << "初始化的棧:" << endl;
	cout << "棧空?" << boolalpha << stack.isEmpty() << endl;
	cout << "棧滿?" << boolalpha << stack.isFull() << endl;
	cout << "**********************" << endl;
	cout << "執行進棧操作後:" << endl;
	for (int i = 0; i < 10; ++i) {
		stack.push(i);
	}
	stack.display();
	cout << "棧中共有" << stack.getSize() << "個元" << endl;
	cout << "棧空?" << boolalpha << stack.isEmpty() << endl;
	cout << "棧滿?" << boolalpha << stack.isFull() << endl;
	cout << "***********************" << endl;
	cout << "執行出棧操作後:" << endl;
	stack.pop();
	stack.display();

	system("pause");
	return 0;
}

程序運行結果如下:

在這裏插入圖片描述

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