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;
}
程序運行結果如下: