Implement two stacks in an array

Implementing two stacks in an array such that, if user wants to push an element in either of two stacks then their should not be an error till the array gets full.

The idea is to start two stacks from the extreme corners of the array. Both these stacks will grow towards each other, stack1 will start from the leftmost corner and stack2 will start from rightmost corner of the array

Algorithm

1. stack1 will start from index 0 and grow towards right end of the array

2. stack2 will start from index n-1 and grow towards left end of the array

3. when both the stacks meet each other then we cant push any element in both stacks

We use push, pop functions to push elements in the both stacks

1. push function will take the stack name and value to be inserted, and pushes the number into respective stack

     a. According to the stack name proceed

     b. Check whether the stack is full or not ie, top1 < top2 -1 Here, top1, top2 are the variables
         to keep track of top elements in both stacks

     c. If not, push the element in the respective stack ie, arr[top1] = k

2. pop will take the stack name and will pop the topmost element in that stack

      a. According to the stack name proceed

      b. check whether their is any element to pop

      c. If yes, decrement or increment the top1, top2 varaibles accordingly

C++ Program

#include <bits/stdc++.h>
#define size 5
using namespace std;

class stacks
{
	int arr[size];
	int top1, top2; //to keep track of stack1, stack2. top elements of stack1 and stack2
public:
	stacks()
	{
		top1 = -1;
		top2 = size;
	}
	void push(string stack, int k) //It will push the elements in the respective stacks
	{
		if(stack == "stack1")
		{
			if(top1 < top2 - 1) //checking whether there is space or not
			{
				top1++;
				arr[top1] = k;
			}
			else
			{
				cout<<"stack1 is full";
			}
		}
		else if(stack == "stack2")
		{
			if(top1 < top2 -1)
			{
				top2--;
				arr[top2] = k;
			}
			else
			{
				cout<<"stack2 is full";
			}
		}
	}
	void pop(string stack) //poping the topmost elemeny
	{
		if(stack=="stack1")
		{
			if(top1 >= 0) //checking whether there is any element in the stack to pop
			{
				cout<<"Element "<<arr[top1]<<" is poped from stack1";
				top1--;
			}
			else
			{
				cout<<"stack1 is empty";
				exit(1);
			}
		}
		else if(stack=="stack2")
		{
			if(top2 < size)
			{
				cout<<"Element "<<arr[top2]<<" is poped from stack2";
				top2++;
			}
			else
			{
				cout<<"stack2 is empty";
				exit(1);
			}
		}

	}	
};
int main()
{
	stacks s; //creating an object for class stacks
	s.push("stack1",5); //It will push the number 5 in stack 1
	s.push("stack2",10);
	s.push("stack1",15);
	s.push("stack2",20);
	s.push("stack1",25);
	s.pop("stack1"); //Top element will be poped from the stack

}
Try It


Next > < Prev
Scroll to Top