完成 quiz4.

This commit is contained in:
A.C.Sukazyo Eyre 2022-10-27 00:01:28 +08:00
commit efd6d81b96
Signed by: Eyre_S
GPG Key ID: C17CE40291207874

95
quiz4/quiz4.cpp Normal file
View File

@ -0,0 +1,95 @@
#include <iostream>
#include <cstring>
#include <sstream>
#include <limits.h>
struct node {
int id;
node* next;
node* prev;
};
void insert_one (node* first, node* curr) {
node* insertion_prev = (*first).prev;
node* insertion_next = first;
(*insertion_next).prev = curr;
(*insertion_prev).next = curr;
(*curr).next = insertion_next;
(*curr).prev = insertion_prev;
}
void remove_one (node* removal) {
node* removal_prev = (*removal).prev;
node* removal_next = (*removal).next;
(*removal_next).prev = removal_prev;
(*removal_prev).next = removal_next;
delete removal;
}
int main () {
int n = 0;
while (n == 0) {
std::string input;
int input_n;
std::cout << "请输入小人个数: ";
std::cin >> input;
try {
input_n = stoi(input);
if (input_n < 1) throw std::exception();
} catch (std::out_of_range) {
std::cout << "你输入的数字 \"" << input << "\" 太大了,它最大只能是 " << INT_MAX << std::endl;
continue;
} catch (std::exception) {
std::cout << "你的输入是 \"" << input << "\", 但小人的数量必须是一个大于 0 的整数!" << std::endl;
continue;
}
std::cout << "小人个数为 " << input_n << " ? [y/n]";
std::cin >> input;
if (input == "y")
n = input_n;
}
node* first = new node;
(*first).id = 1;
(*first).prev = first;
(*first).next = first;
int count = 1;
std::cout << "招募了小人 #" << 1 << " ." << std::endl;
for (int i = 2; i <= n; i++) {
node* curr = new node;
(*curr).id = i;
insert_one(first, curr);
count++;
std::cout << "招募了小人 #" << 1 << " , 它前面是 #" << (*(*curr).prev).id << " , 它后面是 #" << (*(*curr).next).id << std::endl;
}
std::stringstream out_roll;
int counting = 0;
node* next_one = (*first).prev;
while (count > 1) {
node* current = next_one;
next_one = (*next_one).next;
counting++;
std::cout << "小人 #" << (*current).id << " 数到了" << counting;
if (counting == 3) {
out_roll << "#" << (*current).id << " ";
remove_one(current);
counting = 0;
count--;
std::cout << " , 出列!还剩下 " << count << "个小人。";
} else {
std::cout << " .";
}
std::cout << std::endl;
}
std::cout << "=====" << std::endl
<< "最终剩下了小人 #" << (*next_one).id << " !" << std::endl;
std::cout << "小人的出列顺序是: " << out_roll.str() << "." << std::endl;
return 0;
}