2021.9.28数据结构实验课作业

栈的应用:进制转换
使用栈结构,将用户输入的非负十进制数n,将其转换成m(1<m<10)进制数输出。

队列的应用:秋天的第一杯奶茶
使用队列结构,模拟奶茶店的排队服务。受“秋天的第一杯奶茶”影响,奶茶店门口排起了长队,假设店门口最多可容纳M人排队等待。客户到达奶茶店后,首先要自动取号,排在队伍最末尾;工作人员总是先做排在第一位的客户订单。若门口排队人数已满M人,工作人员告知“排队人数太多,请稍后再来”;若所有客户订单全部完成,则提示工作人员休息。

进制转换

点击查看代码
/*
 * 就是基本的进制转换
 * 压到栈里面最后挨个弹出即可
*/
#include <cstdio>
#include <iostream>
using namespace std;

const int Maxn = 1001;
template <typename T>
class Stack {
private:
	int top;
	T sta[Maxn];
public:
	Stack() {
		top = 0;
	}
	Stack(int n, int a[]) {
		top = n;
		for(int i=0; i<n; ++i)
			sta[i] = a[i];
	}
	void Push(T x) {
		if(top == Maxn) throw "Fulled!";
		sta[top++] = x;
	}
	T GetTop() {//只输出,不弹出
		if(Empty()) throw "Empty!";
		return sta[top-1];
	}
	void Pop() {//弹出不输出
		if(Empty()) throw "Empty!";
		--top;
	}
	bool Empty() {
		return top == 0;
	}
};

int main(void) {
	ios::sync_with_stdio(false);
	int n, m;
	Stack<int> s;
	cout << "输入原数字: ";
	cin >> n;
	cout << "输入进制: ";
	cin >> m;
	do {
		s.Push(n%m);
		n /= m;
	}while(n != 0);
	while(!s.Empty()) {
		cout << s.GetTop();
		s.Pop();
	}
	return 0;
}

秋天的第一杯奶茶
话说这个梗到底是什么意思啊。。。。

点击查看代码
/*
 * 基本思路就是维护入队、出队两个函数,记录最新顾客编号
 * 用了循环队列(想加平时分的屑)
 * 不过我好像写的有瑕疵,从第二次队列循环利用开始队列实际可用大小减少1,没想到什么好办法修改
 * 另外,throw后跟字符串常量好像会有异常输出
 * 啧,懒得改了
*/
#include <cstdio>
#include <iostream>
using namespace std;

const int Maxn = 10;
template <typename T>
class Queue {//循环队列
private:
	int first, rear, sum, total;
	T que[Maxn];
public:
	Queue() {
		first = rear = 0;
		sum = total = 0;
	}
	Queue(int n, T a[]) {
		rear = n;
		for(int i=0; i<n; ++i)
			que[i] = a[i];
	}
	void EnQueue() {
		if(rear+1 == first) {
			cout << "排队人数太多,请稍后再来!" << endl;
			return ;
		}
		//cout << rear << endl;
		que[rear++] = ++total;
		cout << "取号成功,单号为: " << total << endl;
		if(rear == Maxn)
			rear = -1;//置为-1可用于判断队列已满 
	}
	void DeQueue() {
		if(Empty()) throw "Empty!";
		cout << "请" << que[first++] << "号顾客取餐" << endl;
		if(first == Maxn)
			first = 0;
		if(rear == -1)//此时可以确认队列0位置为空 
			++rear;//这样会导致从第二次使用0位置开始队列会少一个位置,但我实在不知道咋改 
		if(Empty())
			cout << "请工作人员休息" << endl;
	}
	T GetQueue() {
		if(Empty()) throw "Empty!";
		return que[first];
	}
	bool Empty() {
		return first == rear;
	}
};

int main(void) {
	ios::sync_with_stdio(false);
	int x;
	Queue<int> q;
	do {
		cin >> x;
		switch(x) {
			case 1:
				q.EnQueue();
				break;
			case 2:
				q.DeQueue();
				break;
		}
	}while(x != 0);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章