From 26f9d6363e4621f1df1be4b1a40e1497885a3e13 Mon Sep 17 00:00:00 2001 From: qualifier1024 <102360259+qualifier1024@users.noreply.github.com> Date: Mon, 28 Nov 2022 09:32:05 +0800 Subject: [PATCH 1/2] Update PrintUtil.hpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充了stack打印方法,形式为"top->num1, num2]" 我不确定这么做是否规范 --- codes/cpp/include/PrintUtil.hpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/codes/cpp/include/PrintUtil.hpp b/codes/cpp/include/PrintUtil.hpp index b85da88ef..703c7b8fa 100644 --- a/codes/cpp/include/PrintUtil.hpp +++ b/codes/cpp/include/PrintUtil.hpp @@ -210,4 +210,34 @@ class PrintUtil { printTree(root->left, trunk, false); } + /** + * @brief Get the Stack String object + * + * @tparam T + * @param stack + * @return string + */ + template + static string getStackString(stack stack) { + ostringstream s; + if(!stack.empty()){ + s << stack.top(); + stack.pop(); + } + while(!stack.empty()){ + s << ", " << stack.top(); + stack.pop(); + } + return "top->" + s.str() + "]"; + } + /** + * @brief Print a stack + * + * @tparam T + * @param stack + */ + template + static void printStack(stack &stack) { + cout << getStackString(stack) << '\n'; + } }; From a8afc963b6f6a9b6998b84d998226a6aeb7ffc4c Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Mon, 28 Nov 2022 20:51:12 +0800 Subject: [PATCH 2/2] Update PrintUtil.hpp Reverse the stack before printing. --- codes/cpp/include/PrintUtil.hpp | 42 ++++++++++++++++----------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/codes/cpp/include/PrintUtil.hpp b/codes/cpp/include/PrintUtil.hpp index 703c7b8fa..f326f78d1 100644 --- a/codes/cpp/include/PrintUtil.hpp +++ b/codes/cpp/include/PrintUtil.hpp @@ -210,34 +210,32 @@ class PrintUtil { printTree(root->left, trunk, false); } + /** - * @brief Get the Stack String object + * @brief Print a stack * * @tparam T - * @param stack - * @return string + * @param stk */ template - static string getStackString(stack stack) { - ostringstream s; - if(!stack.empty()){ - s << stack.top(); - stack.pop(); + static void printStack(stack &stk) { + // Reverse the input stack + stack tmp; + while(!stk.empty()) { + tmp.push(stk.top()); + stk.pop(); } - while(!stack.empty()){ - s << ", " << stack.top(); - stack.pop(); + // Generate the string to print + ostringstream s; + bool flag = true; + while(!tmp.empty()) { + if (flag) { + s << tmp.top(); + flag = false; + } + else s << ", " << tmp.top(); + tmp.pop(); } - return "top->" + s.str() + "]"; - } - /** - * @brief Print a stack - * - * @tparam T - * @param stack - */ - template - static void printStack(stack &stack) { - cout << getStackString(stack) << '\n'; + cout << "[" + s.str() + "]" << '\n'; } };