栈和队列的实现

23 篇文章 0 订阅
/**
 * @brief Stack and Queue 
 * @author An
 * @data  2013.5.21                                                                  
**/
#ifndef STACKANDQUEUE_H
#define STACKANDQUEUE_H
#define stackSize 50
#define queueSize 50
#include <iostream>
using namespace std;

template <class Type>
class Stack
{
public:
	Stack(): index( -1 ) { }
	bool empty()
	{
		if ( index == -1)
			return true;
		else
			return false;
	}
	int maxSize()
	{
		return stackSize;
	}
	int size()
	{
		return index + 1;
	}
	Type top()
	{
		if ( empty() )
		{
			cout << "ERROR: The Stack is empty! " << endl;
			return -1;
		}
		return array[ index ];
	}
	void push( Type newElem )
	{
		if ( index >= stackSize - 1 )
		{
			cout << "The stack is full!" << endl;
		}
		else
		{
			++index;
			array[ index ] = newElem;
		}
	}
	void pop()
	{
		if ( index == -1 )
		{
			cout << "The stack is empty!" << endl;
		}
		else
		{
			--index;
		}
	}
private:
	Type array[ stackSize ];
	int index;
};


template <class Type>
class Queue
{
public:
	Queue(): head(0), tail(0) {}
	bool empty()
	{
		if ( head == tail )
			return true;
		else
			return false;
	}
	int size()
	{
		if ( tail >= head )
			return tail - head;
		else
			return tail - head + queueSize;
	}
	int maxSize()
	{
		return queueSize;
	}
	Type front()
	{
		if ( empty() )
		{
			cout << "The queue is empty!" << endl;
			return -1;
		}
		else
		{
			return array[ head ];
		}
	}
	Type back()
	{
		if ( empty() )
		{
			cout << "The queue is empty!" << endl;
			return -1;
		}
		if ( tail > 0 )
			return array[ tail - 1 ];
		else
			return array[ queueSize ];
	}
	void EnQueue( Type newElem )
	{
		if ( (tail + 1) % queueSize == head )
		{
			cout << "The queue is full!" << endl;
		}
		else
		{
			array[ tail ] = newElem;
			if ( tail == queueSize - 1 )
				tail = 0;
			else
				++tail;
		}
	}
	Type DeQueue()
	{
		if ( empty() )
		{
			cout << "The queue is empty!" << endl;
			return -1;
		}
		Type tmp = array[ head ];
		if ( head == queueSize - 1 )
			head = 0;
		else
			++head;
		return tmp;
	}
private:
	Type array[ queueSize ];
	int head;
	int tail;
};




#endif


 

#include "StackAndQueue.h"
#include <iostream>
using namespace std;

int main()
{
	Stack<int> stk;
	Queue<int> que;
	for ( int i = 0; i <= 9; ++i )
	{
		stk.push( i );
	}
	for ( int i = 0; i <= 9; ++i )
	{
		que.EnQueue( stk.top() );
		cout << que.back() << " ";
		stk.pop();
	}
	cout << endl;
	for ( int i = 0; i <= 9; ++i )
	{
		cout << que.DeQueue() << " ";
	}
	cout << endl;
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值