C++用数组实现栈和循环队列

时间:2021-12-13 03:59:10

栈的实现:

#include<iostream>
#include<string>
using namespace std;
#define size 5
class zhan
{
public:
	zhan()
	{
		number=0;
	}
	void push(int c)
	{
		if(number==size)
		{
			cout<<"栈已经满了,无法在插入了"<<endl;
			return ;
		}
		else
		{
			number++;
			a[number]=c;
		}
	}
	void pop()
	{
		if(number==0)
		{
			cout<<"栈已经空"<<endl;
			return ;
		}
		else
		{
			cout<<"出栈元素是"<<a[number]<<endl;
			number--;
		}
	}
	void show()
	{
		cout<<"栈里现在有元素的个数是"<<number<<endl;
	}
private:
	int a[size];
	int number;
};
int main()
{
	class zhan zhan1;
	int c;
	string str1;
	cout<<"输入y进行入栈输入n进行出栈,输入k显示当前栈中元素的个数,输入x退出"<<endl;
	cin>>str1;
	while(str1[0]!='x')
	{
		if(str1[0]=='y')
		{
			cout<<"输入你要入栈的元素"<<endl;
			cin>>c;
			zhan1.push(c);
		}
		else if(str1[0]=='n')
		{
			zhan1.pop();
		}
		else if(str1[0]=='k')
			zhan1.show();
		cout<<"输入y进行入栈输入n进行出栈,输入k显示当前栈中元素的个数,输入x退出"<<endl;
		cin>>str1;
	}
	return 0;
}

效果:

http://hiphotos.baidu.com/%B7%E7%C7%E5%D1%EFsong%B7%E7%C7%E5%D1%EFsong/pic/item/f2c50d63ff9f629a8cb10d10.jpg

队列的实现:

#include<iostream>
#include<string>
using namespace std;
#define size 3
class deque
{
public:
	deque();
	void ru_dui(int);
	void chu_dui();
	void show();
private:
	int front;
	int end;
	int number;
	int a[size];
};
deque::deque()
{
	front=end=number=0;
}
void deque:: ru_dui(int c)
{
	if(number==size)
	{
		cout<<"队列满了无法插入元素"<<endl;
		return;
	}
	else
	{
		number++;
		a[end]=c;
		end=(end+1)%size;
	}
}
void deque::chu_dui()
{
	if(number==0)
	{
		cout<<"队列空"<<endl;
		return ;
	}
	else
	{
		number--;
		cout<<"出队元素是"<<a[front]<<endl;
		front=(front+1)%size;

	}
}
void deque::show()
{
	cout<<"队列中元素的个数是"<<number<<endl;
}
int main()
{
	class deque que1;
	string str1;
	cout<<"输入y入队,输入n出队,输入k查看队列元素个数,输入x退出"<<endl;
	cin>>str1;
	while(str1[0]!='x')
	{
		if(str1[0]=='y')
		{
			int c;
			cout<<"输入入队列元素"<<endl;
			cin>>c;
			que1.ru_dui(c);
		}
		else if(str1[0]=='n')
			que1.chu_dui();
		else if(str1[0]=='k')
			que1.show();
		else;
		cout<<"输入y入队,输入n出队,输入k查看队列元素个数,输入x退出"<<endl;
		cin>>str1;
	}
	return 0;
}

效果:

http://hiphotos.baidu.com/%B7%E7%C7%E5%D1%EFsong%B7%E7%C7%E5%D1%EFsong/pic/item/b9c2fec0510f3610b219a81f.jpg

转载自:http://hi.baidu.com/%B7%E7%C7%E5%D1%EFsong%B7%E7%C7%E5%D1%EFsong/blog/item/851b270afd8386a12fddd4df.html