1. 程式人生 > >資料結構(C++)-用順序結構實現的棧模板類

資料結構(C++)-用順序結構實現的棧模板類

棧:last in first out

1.MStackADT.h

 #ifndef MSTACKADT_H
#define MSTACKADT_H
/*
Create by軟體工程 gpwner 2016年11月20日
*/
template<class T>
class MStackADT
{
public:
    MStackADT();
    virtual ~MStackADT();
    //棧的初始化
    virtual void initializeStack() = 0;
    //棧是否為空
    virtual bool isEmptyStack() const
= 0; //棧是否已滿 virtual bool isFullStack() const = 0; //插入資料 virtual void push(const T& newItem) = 0; //獲取棧中的資料 virtual T top() const = 0; //彈出資料 virtual void pop() = 0; private: }; #endif // MSTACKADT_H

2.MStack.h

#ifndef STACKTYPE_H
#define STACKTYPE_H
#include<MStackADT.h>
#include <iostream> #include <cassert> using namespace std; template <class T> class stackType: public MStackADT<T> { public: const stackType<T>& operator=(const stackType<T>&); void initializeStack() { stackTop = 0; } bool isEmptyStack() const
{ return(stackTop == 0); } bool isFullStack() const { return(stackTop == maxStackSize); } void push(const T& newItem) { if (!isFullStack()) { arr[stackTop] = newItem; //add newItem to the //top of the stack stackTop++; //increment stackTop } else cout << "Cannot add to a full stack." << endl; } T top() const { assert(stackTop != 0); //if stack is empty, //terminate the program return arr[stackTop - 1]; } void pop() { if (!isEmptyStack()) stackTop--; //decrement stackTop else cout << "Cannot remove from an empty stack." << endl; } stackType(int stackSize = 100) { if (stackSize <= 0) { cout << "Size of the array to hold the stack must " << "be positive." << endl; cout << "Creating an array of size 100." << endl; maxStackSize = 100; } else maxStackSize = stackSize; stackTop = 0; arr = new T[maxStackSize]; //create the array to } stackType(const stackType<T>& otherStack) { delete [] arr; maxStackSize = otherStack.maxStackSize; stackTop = otherStack.stackTop; arr = new T[maxStackSize]; //copy otherStack into this stack for (int j = 0; j < stackTop; j++) arr[j] = otherStack.arr[j]; } ~stackType() { delete [] arr; // } private: int maxStackSize; int stackTop; T *arr; void copyStack(const stackType<T>& otherStack); }; #endif // STACKTYPE_H

注意:在code blocks下,模板類的方法的實現是不能在.cpp檔案中寫的,必須在.h檔案中寫。否則會報錯,說你的模板的類沒有實現。