【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)

前端之家收集整理的这篇文章主要介绍了【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)

//头文件

#ifndef _SEQ_STACK_
#define _SEQ_STACK_


#include <iostream>
using namespace std;


template <class Type>
class SeqStack
{
public:
	SeqStack(size_t sz=INIT_SIZE)
	{
		capacity = sz > INIT_SIZE ? sz : INIT_SIZE;
		base = new Type[capacity];
		top = 0;
	}
	~SeqStack()
	{
		destory();
	}
public:


	bool empty() const                  //判断是否为空
	{
		return(top == 0);
	}




	bool full()const                   //判断是否已满
	{
		return(top >= capacity);
	}




	void push(const Type &x)           //进栈
	{
		if (full() )
		{
			cout << "栈已满,不能插入。" << endl;
			return;
		}
		base[top++] = x;
	}




	void pop()                         //出栈
	{
		top--;
	}




	bool getTop(Type &x) const        //获得栈顶
	{
		if (top == 0)
			return false;
		x = base[top - 1];
		return true;
	}




	int length() const                //求大小
	{
		return top;
	}




	void clear()                     //清除
	{
		top = 0;
	}
	
	
	void destory()                   //摧毁
	{
		delete[]base;
		base = NULL;
		capacity = top = 0;
	}




	void show() const                //显示
	{
		if (empty() == 1)
		{
			cout << "栈为空" << endl;
			return;
		}
		for (int i=top-1; i >=0; i--)
		{
			cout << base[i]<<endl;
		}
	}
private:
	enum {INIT_SIZE = 8 };
	Type *base;
	int capacity;
	int top;
};


#endif

//主函数

#include "SeqStack.h"


void main()
{
	SeqStack<int> mystack;
	int select = 1;
	int Item;
	while (select)
	{
		cout << "**************************************" << endl;
		cout << "* [1] show            [2] push       *" << endl;
		cout << "* [3] pop             [4] length     *" << endl;
		cout << "* [5] clear           [6] destory    *" << endl;
		cout << "**************************************" << endl;
		cout << "请选择:>";
		cin >> select;
		switch (select)
		{
		case 1:
			mystack.show();
			break;
		case 2:
			cout << "请输入要插入的值(-1结束):>";
			while (cin >> Item,Item != -1)
			{
				mystack.push(Item);
			}
			break;
		case 3:
			mystack.pop();
			break;
		case 4:
			cout << "大小为:" << mystack.length()<<endl;
			break;
		case 5:
			mystack.clear();
			break;
		case 6:
			mystack.destory();
			break;
		default:
			break;
		}
	}
	return;
}
<img src="http://img.blog.csdn.net/20150531225418525?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

原文链接:https://www.f2er.com/datastructure/382643.html

猜你在找的数据结构相关文章