From 4ab54cbc2c38590d583443d5b36d07cef5f143fb Mon Sep 17 00:00:00 2001 From: Eyre_S Date: Wed, 26 Oct 2022 23:44:46 +0800 Subject: [PATCH] =?UTF-8?q?quiz4:=20=E5=AE=8C=E6=88=90=E4=BA=86=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E7=89=88=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=BA=86=E5=BF=98?= =?UTF-8?q?=E8=AE=B0=E8=87=AA=E5=87=8F=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- quiz4/quiz4.cpp | 88 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 quiz4/quiz4.cpp diff --git a/quiz4/quiz4.cpp b/quiz4/quiz4.cpp new file mode 100644 index 0000000..af1dddf --- /dev/null +++ b/quiz4/quiz4.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +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; + +}