quiz4: 完成了第一版,修复了忘记自减的问题

This commit is contained in:
A.C.Sukazyo Eyre 2022-10-26 23:44:46 +08:00
parent f2fce430ad
commit 4ab54cbc2c
Signed by: Eyre_S
GPG Key ID: C17CE40291207874

88
quiz4/quiz4.cpp Normal file
View File

@ -0,0 +1,88 @@
#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 = 0;
(*first).prev = first;
(*first).next = first;
int count = 1;
for (int i = 2; i <= n; i++) {
node* curr = new node;
(*curr).id = i;
insert_one(first, curr);
count++;
}
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
<< "最终剩下了小人 #" << (*first).id << " !" << std::endl;
return 0;
}