顺序栈(C++)

栈的定义为只允许在表的末端进行插入和删除的线性表。简而言之就是先进后出的线性表

插入和删除的一端被称呼为栈顶(top),而不允许插入删除的一端被称为栈底(bottom)。无元素时的栈即为空栈。

 

 

使用一维数组实现栈

//stack.h
#ifndef STACK_H
#define STACK_H
#include<iostream>
#include<assert.h>
using namespace std;
const int maxSize = 50;


template<class T>
class Stack
{
public:
	Stack(){};
	virtual void Push(const T& x) = 0;
	virtual void Pop(T& x) = 0;
	virtual bool getTop(T& x) = 0;
	virtual bool IsEmpty()const = 0;
	virtual bool IsFull()const = 0;
	virtual int getSize()const = 0;
};
#endif

 

//main.cpp


#include"stack.h" const int stackIncreament = 20; template<class T> class SeqStack : public Stack<T> { private: T *elements; //栈数组 int top; //栈顶指针 int maxSize;//栈的大小 void overflowProcess();//自动扩容函数 public: SeqStack(int sz = 50); ~SeqStack(){delete[]this->elements;} void Push(const T& x);//向栈中压入元素 void Pop(T& x);//出栈 bool getTop(T& x);//获取栈顶元素 bool IsEmpty()const{return (this->top==-1 ? true : false);} bool IsFull()const{return (this->top+1==this->maxSize ? true : false);} int getSize()const{return this->top+1;} void MakeEmpty(){this->top = -1;}//使栈空 void print(); friend ostream& operator<<(ostream& out, SeqStack<T>& s)//声明为友元函数,重载输出运算符<< { out<<"top = "<<s.top<<endl; for(int i=0; i<=s.top; ++i) out<<i<<":"<<s.elements[i]<<endl; return out; } }; template<class T> void SeqStack<T>::print() { if(!this->IsEmpty()) { for(int i=this->top; i>=0; --i) cout<<" ["<<this->elements[i]<<"] "; cout<<endl; } } template<class T> void SeqStack<T>::Push(const T& x) { if(!this->IsFull()) { ++this->top; this->elements[this->top] = x; } else { this->overflowProcess(); this->elements[this->top] = x; ++this->top; } }; template<class T> void SeqStack<T>::Pop(T& x) { if(!this->IsEmpty()) { x = this->elements[this->top]; --this->top; } }; template<class T> bool SeqStack<T>::getTop(T& x) { if(!this->IsEmpty()) { x = this->elements[this->top-1]; return true; } return false; }; template<class T> void SeqStack<T>::overflowProcess() { T *newArry = new T[maxSize+stackIncreament]; if(newArry == NULL) { cout<<"内存分配失败!"<<endl; exit(1); } for(int i=0; i<this->maxSize; ++i) newArry[i] = this->elements[i]; this->maxSize = this->maxSize+stackIncreament; delete[]this->elements; this->elements = newArry; }; template<class T> SeqStack<T>::SeqStack(int sz):top(-1),maxSize(sz) { this->elements = new T[this->maxSize]; assert(this->elements != NULL); }; int main() { SeqStack<int> ss; for(int i=0; i<60; ++i) ss.Push(i); int i = int(); ss.Pop(i); cout<<i<<endl; ss.print(); cout<<ss<<endl; return 0; }

 试试执行效果

 

 因为换行过多没有将整幅图上传。

posted @ 2019-05-31 18:30  C_hp  阅读(310)  评论(0)    收藏  举报