Answers for "k stacks in an array"

C++
0

k stacks in an array

//Program in C++ to implement k stacks in an array

#include <iostream>
using namespace std;

class kstack{
  int *s; //stack
  int *index; //prev occupied and next available indexes of stack
  int *top_of_stack; //top of every stack
  int next_available; //next available index
  
  public:
  //initialize every value
  kstack(int capacity,int number_of_stacks){
      s = new int[capacity];
      index = new int[capacity];
      top_of_stack = new int[number_of_stacks];
      next_available = 0;
      
      for(int i=0;i<capacity;i++)
          index[i] = (i != capacity-1)?i+1 : -1;
      
      for(int i=0;i<number_of_stacks;i++)
          top_of_stack[i] = -1;
  }
  
  void push(int,int); //push given element to given stack no.
  void pop(int); //pop an element from given stack no.
};

void kstack::push(int stack_num,int value){
    if(next_available == -1){
        cout<<"All Stacks overflowed\n";
        return;
    }
    
    int free_index = index[next_available];
    
    //set new value
    s[next_available] = value;
    
    //set prev index for current stack's top index
    index[next_available] = top_of_stack[stack_num];
    
    //set top of stack to curr index
    top_of_stack[stack_num] = next_available;
    
    //set next next_available to next free index
    next_available = free_index;
    
    cout<<"Element pushed successfully\n";
}

void kstack::pop(int stack_num){
    int top_index = top_of_stack[stack_num];
    
    if(top_index == -1) 
        cout<<"Stack "<<stack_num<<" is empty!\n";
    
    int top_element = s[top_of_stack[stack_num]];
    cout<<top_element<<" poped\n";
    
    //set top of stack to prev top of stack
    top_of_stack[stack_num] = index[top_index];
    
    //set index to point to next available index
    index[top_index] = next_available;
    
    //set next available to current poped index
    next_available = top_index;
}

int main() {
    //instantiate kstack
	kstack s(6,3);
	//push elements to respective given stack
	s.push(0,2);
	s.push(0,15);
	s.push(2,10);
	s.push(1,4);
	s.pop(0);
	s.push(2,3);
	s.pop(2);
	s.push(2,5);
	s.push(2,6);
	s.push(3,7);
	s.push(2,8); //whole stack array is full at this point
	return 0;
}
Posted by: Guest on September-21-2021

Browse Popular Code Answers by Language