⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stack.cpp

📁 自己写的堆栈算法
💻 CPP
字号:
// Stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//#include "StkSequence.h"
//#include <iostream.h>
#include <assert.h>
#include <iostream>
using namespace std;


const int AddNum = 5;

template <class Type> class Stack{
private:
	int top;
	Type *elements;
	int MaxSize;
public:
	Stack(int=10);
	~Stack(){delete[] elements;}
	void Push(const Type &item);
	Type Pop();
	Type GetTop();
	void MakeEmpty(){top=-1;}
	int IsEmpty() const{return top == -1;}
	int IsFull() const{return top == MaxSize-1;}
	void Inflate(int increase);
};


int main(int argc, char* argv[])
{
	Stack<int> stack(5);
	for (int i=0; i<310; i++)
		stack.Push(i);
	int count = 0;
	while(!stack.IsEmpty()){
		if (count%5 == 0) cout << endl;
		cout << stack.Pop() << '\t';
		count++;
	}
	return 0;
}



template <class Type> Stack<Type>::Stack(int s):top(-1),MaxSize(s){
	elements = new Type[MaxSize];
	assert(elements != 0);
}

template <class Type> void Stack<Type>::Push(const Type &item){
//	assert(!IsFull());
	if (IsFull()) Inflate(AddNum);
	elements[++top] = item;
}

template <class Type> Type Stack<Type>::Pop(){
	assert(!IsEmpty());
	return elements[top--];
}

template <class Type> Type Stack<Type>::GetTop(){
	assert(!IsEmpty());
	return elements[top];
}

template <class Type> void Stack<Type>::Inflate(int increase){
	if (increase <= 0){
		cout << "Increase is " << increase << "invalid!" << endl;
		return;
	}
	int tempNum = MaxSize+increase;
	Type *tElements = new Type[tempNum];
	for (int i=0; i<MaxSize; i++){
		tElements[i] = elements[i];
	}
	delete []elements;
	MaxSize = tempNum;
	elements = tElements;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -