{"id":26940,"date":"2017-12-28T22:02:35","date_gmt":"2017-12-28T16:32:35","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26940"},"modified":"2017-12-28T22:02:35","modified_gmt":"2017-12-28T16:32:35","slug":"java-algorithm-implement-two-stacks-array","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-implement-two-stacks-array\/","title":{"rendered":"Java Algorithm &#8211; Implement two stacks in an array"},"content":{"rendered":"<p>Create a data structure <em>twoStacks <\/em>that represents two stacks. Implementation of <em>twoStacks <\/em>should use only one array, i.e., both stacks should use the same array for storing elements. Following functions must be supported by <em>twoStacks<\/em>.<span id=\"more-18754\"><\/span><\/p>\n<p>push1(int x) \u2013&gt; pushes x to first stack<br \/>\npush2(int x) \u2013&gt; pushes x to second stack<\/p>\n<p>pop1() \u2013&gt; pops an element from first stack and return the popped element<br \/>\npop2() \u2013&gt; pops an element from second stack and return the popped element<\/p>\n<p>Implementation of <em>twoStack <\/em>should be space efficient.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 1 (Divide the space in two halves)<\/strong><br \/>\nA simple way to implement two stacks is to divide the array in two halves and assign the half half space to two stacks, i.e., use arr[0] to arr[n\/2] for stack1, and arr[n\/2+1] to arr[n-1] for stack2 where arr[] is the array to be used to implement two stacks and size of array be n.<\/p>\n<p>The problem with this method is inefficient use of array space. A stack push operation may result in stack overflow even if there is space available in arr[]. For example, say the array size is 6 and we push 3 elements to stack1 and do not push anything to second stack2. When we push 4th element to stack1, there will be overflow even if we have space for 3 more elements in array.<\/p>\n<p><strong>Method 2 (A space efficient implementation)<\/strong><br \/>\nThis method efficiently utilizes the available space. It doesn\u2019t cause an overflow if there is space available in arr[]. The idea is to start two stacks from two extreme corners of arr[]. stack1 starts from the leftmost element, the first element in stack1 is pushed at index 0. The stack2 starts from the rightmost corner, the first element in stack2 is pushed at index (n-1). Both stacks grow (or shrink) in opposite direction. To check for overflow, all we need to check is for space between top elements of both stacks. This check is highlighted in the below code.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to implement two stacks in a<br\/>\/\/ single array<br\/>class TwoStacks<br\/>{<br\/>    int size;<br\/>    int top1, top2;<br\/>    int arr[];<br\/> <br\/>    \/\/ Constructor<br\/>    TwoStacks(int n)<br\/>    {<br\/>        arr = new int[n];<br\/>        size = n;<br\/>        top1 = -1;<br\/>        top2 = size;<br\/>    }<br\/> <br\/>    \/\/ Method to push an element x to stack1<br\/>    void push1(int x)<br\/>    {<br\/>        \/\/ There is at least one empty space for<br\/>        \/\/ new element<br\/>        if (top1 &lt; top2 - 1)<br\/>        {<br\/>            top1++;<br\/>            arr[top1] = x;<br\/>        }<br\/>        else<br\/>        {<br\/>            System.out.println(&quot;Stack Overflow&quot;);<br\/>            System.exit(1);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Method to push an element x to stack2<br\/>    void push2(int x)<br\/>    {<br\/>        \/\/ There is at least one empty space for<br\/>        \/\/ new element<br\/>        if (top1 &lt; top2 -1)<br\/>        {<br\/>            top2--;<br\/>            arr[top2] = x;<br\/>        }<br\/>        else<br\/>        {<br\/>            System.out.println(&quot;Stack Overflow&quot;);<br\/>            System.exit(1);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Method to pop an element from first stack<br\/>    int pop1()<br\/>    {<br\/>        if (top1 &gt;= 0)<br\/>        {<br\/>            int x = arr[top1];<br\/>            top1--;<br\/>            return x;<br\/>        }<br\/>        else<br\/>        {<br\/>            System.out.println(&quot;Stack Underflow&quot;);<br\/>            System.exit(1);<br\/>        }<br\/>        return 0;<br\/>    }<br\/> <br\/>    \/\/ Method to pop an element from second stack<br\/>    int pop2()<br\/>    {<br\/>        if(top2 &lt; size)<br\/>        {<br\/>            int x =arr[top2];<br\/>            top2++;<br\/>            return x;<br\/>        }<br\/>        else<br\/>        {<br\/>            System.out.println(&quot;Stack Underflow&quot;);<br\/>            System.exit(1);<br\/> <br\/>        }<br\/>        return 0;<br\/>    }<br\/> <br\/>    \/\/ Driver program to test twoStack class<br\/>    public static void main(String args[])<br\/>    {<br\/>        TwoStacks ts = new TwoStacks(5);<br\/>        ts.push1(5);<br\/>        ts.push2(10);<br\/>        ts.push2(15);<br\/>        ts.push1(11);<br\/>        ts.push2(7);<br\/>        System.out.println(&quot;Popped element from&quot; +<br\/>                           &quot; stack1 is &quot; + ts.pop1());<br\/>        ts.push2(40);<br\/>        System.out.println(&quot;Popped element from&quot; +<br\/>                         &quot; stack2 is &quot; + ts.pop2());<br\/>    }<br\/>}<br\/>\/\/ This code has been contributed by<br\/>\/\/ Amit Khandelwal(Amit Khandelwal 1).<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>  Popped element from stack1 is 11\r\n  Popped element from stack2 is 40\r\n<\/pre>\n<p>Time complexity of all 4 operations of <em>twoStack <\/em>is O(1).<br \/>\nWe will extend to 3 stacks in an array in a separate post.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Implement two stacks in an array &#8211; Data Structure &#8211; Create a data structure twoStacks that represents two stacks.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2139,79607],"tags":[80438,80528,80446,80443,80442,80445,80485,80441,80440,80444],"class_list":["post-26940","post","type-post","status-publish","format-standard","hentry","category-java","category-stack","tag-3-stacks-in-an-array","tag-algorithm-for-multiple-stack","tag-algorithm-to-implement-two-stacks-in-one-array","tag-implement-k-stacks-in-a-single-array","tag-implement-multiple-stacks-in-a-single-dimensional-array-algorithm","tag-implement-two-stacks-using-one-array-java","tag-implementation-of-stack-using-array-in-data-structure","tag-multiple-stack-in-data-structure","tag-multiple-stack-using-array-in-c","tag-two-way-stack-implementation-in-c-using-array"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26940","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26940"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26940\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26940"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26940"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26940"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}