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'; } };