fjut-quiz-2022-10-26/quiz4/quiz4.cpp

91 lines
2.2 KiB
C++

#include <iostream>
#include <cstring>
#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;
}
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) {
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;
return 0;
}