{"id":924,"date":"2023-01-13T09:45:28","date_gmt":"2023-01-13T01:45:28","guid":{"rendered":"https:\/\/swordofmorning.com\/?p=924"},"modified":"2025-10-09T13:55:19","modified_gmt":"2025-10-09T05:55:19","slug":"implement-queue-and-sort-via-stack","status":"publish","type":"post","link":"https:\/\/swordofmorning.com\/index.php\/2023\/01\/13\/implement-queue-and-sort-via-stack\/","title":{"rendered":"Implement Queue and Sort via Stack"},"content":{"rendered":"<p><div class=\"has-toc have-toc\"><\/div><\/p>\n<p>&emsp;&emsp;In this article we'll discuss how to implement queue and sort by stack. All these methods need to use two stacks.<\/p>\n<h2>\u00a71 Queue<\/h2>\n<p>&emsp;&emsp;Here we have a stack <code>st1<\/code>, and we'll use a temporary stack <code>st2<\/code> to reverse <code>st1<\/code>. So, we can give method one:<\/p>\n<ol>\n<li>in queue: directly in <code>st1<\/code>.<\/li>\n<li>out queue: reverse <code>st1<\/code> to <code>st2<\/code>, next pop the top, then reverse <code>st2<\/code> to <code>st1<\/code>.<\/li>\n<\/ol>\n<p>&emsp;&emsp;This is the common method to achieve, to reduce the operation steps, we can have method two:<\/p>\n<ol>\n<li>in queue: directly in <code>st1<\/code>.<\/li>\n<li>out queue: <strong>if<\/strong> <code>st2<\/code> not empty, pop from <code>st2<\/code>; <strong>else if<\/strong> <code>st2<\/code> empty, reverse <code>st1<\/code> to <code>st2<\/code>, then pop from <code>st2<\/code>.<\/li>\n<\/ol>\n<p>Here is C++ example code:<\/p>\n<pre><code class=\"language-cpp\">\/\/ use stack to implement queue.\ntemplate&lt;typename elemType&gt;\nclass stque {\nprivate:\n    std::stack&lt;elemType&gt; m_st1;\n    std::stack&lt;elemType&gt; m_st2;\n\npublic:\n    stque() { \/* do nothing *\/ }\n\n    void reverse()\n    {\n        while (!m_st1.empty())\n        {\n            m_st2.push(m_st1.top());\n            m_st1.pop();\n        }\n    }\n\n    void push(elemType ele)\n    {\n        m_st1.push(ele);\n    }\n\n    elemType pop()\n    {\n        \/\/ if st2 empty, reverse st1 to st2 first, then pop.\n        if (m_st2.empty())\n        {\n            this-&gt;reverse();\n        }\n\n        \/\/ if st2 not empty, directly pop.\n        elemType retval = m_st2.top();\n        m_st2.pop();\n        return retval;\n    }\n};<\/code><\/pre>\n<h2>\u00a72 Sort<\/h2>\n<p>&emsp;&emsp;Sort have the same idea with queue, here is my method. we have <code>st1<\/code> which is to be sorted and sorted stack <code>st2<\/code> i.e. the output. We use <code>lt &lt;<\/code> as order principle.<\/p>\n<p><!-- 1. Firstly, We'll push all elements into <code>st1<\/code>.\n2. Then move one element from <code>st1<\/code> to <code>st2<\/code>.\n3. While <code>st1<\/code> is not empty, we compare the <code>st1.top<\/code> and <code>st2.top<\/code>, if <code>st1.top &lt; st2.top<\/code>, then we just need to push <code>st2.top<\/code> into <code>st1<\/code>; else if <code>st1.top &gt;= st2.top<\/code>, we need to push the <code>st2.top<\/code> into <code>st1<\/code>, then use --><\/p>\n<blockquote>\n<p>that is, each time an element a is popped from the stack s, and the size of the top element b on the stack between it and s2 is judged, if a is less than or equal to b, then it is pushed to s2, otherwise, s2 is popped and merged Stack to s until the top element of s2 happens to be smaller than a, put a on the stack s2, repeat the above steps until s is empty.<\/p>\n<\/blockquote>\n<p>Here is an example code:<\/p>\n<pre><code class=\"language-cpp\">\/\/ use stack to implement sort.\ntemplate&lt;typename elemType&gt;\nclass stsort {\npublic:\n    \/\/ sort principle: &lt;, for st2: small nums on top, big nums in bottom\n    std::stack&lt;elemType&gt; sort(std::stack&lt;elemType&gt; st1)\n    {\n        std::stack&lt;elemType&gt; st2;\n\n        st2.push(st1.top());\n        st1.pop();\n\n        while (!st1.empty())\n        {\n            elemType st1Top = st1.top();\n            st1.pop();\n\n        loop:\n            elemType st2Top = st2.top();\n            st2.pop();\n            if (st1Top &lt; st2Top)\n            {\n                st2.push(st2Top);\n                st2.push(st1Top);\n            }\n            else\n            {\n                st1.push(st2Top);\n                if (st2.empty())\n                {\n                    st2.push(st1Top);\n                    continue;\n                }\n                goto loop;\n            }\n        }\n        return st2;\n    }\n};<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>&emsp;&emsp;In this article we&#8217;ll discuss how to implement queue  &#823","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[48],"tags":[14],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/posts\/924"}],"collection":[{"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/comments?post=924"}],"version-history":[{"count":1,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/posts\/924\/revisions"}],"predecessor-version":[{"id":925,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/posts\/924\/revisions\/925"}],"wp:attachment":[{"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/media?parent=924"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/categories?post=924"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/swordofmorning.com\/index.php\/wp-json\/wp\/v2\/tags?post=924"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}