棧的應用:進制轉換
使用棧結構,將用戶輸入的非負十進制數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;
}