HamletPetrosyan

Untitled

Oct 27th, 2021
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. interface IntStack {
  2.     void push(int item);
  3.     int pop();
  4. }
  5.  
  6. class Stack implements IntStack {
  7.     private int stck[];
  8.     private int tos;
  9.  
  10.     Stack(int size) {
  11.         stck = new int[size];
  12.         tos = -1;
  13.     }
  14.  
  15.     public boolean isEmpty(){
  16.         if(tos > -1){
  17.             return true;
  18.         }
  19.         return false;
  20.     }
  21.  
  22.     // Push
  23.     public void push(int item) {
  24.         if(tos==stck.length-1)
  25.             System.out.println("Stack is full.");
  26.         else
  27.             stck[++tos] = item;
  28.     }
  29.  
  30.     // Pop
  31.     public int pop() {
  32.         if(tos < 0) {
  33.             System.out.println("Stack underflow.");
  34.             return 0;
  35.         }
  36.         else
  37.             return stck[tos--];
  38.     }
  39. }
  40.  
  41.  
  42. class Queue {
  43.     Stack st1, st2;
  44.  
  45.     Queue(){
  46.         st1 = Stack(5);
  47.         st2 = Stack(5);
  48.     }
  49.  
  50.     void enqueue(int x){
  51.         st1.push(x);
  52.     }
  53.  
  54.     int dequeue(){
  55.         int x;
  56.         while(!st1.isEmpty()){
  57.             x = st1.pop();
  58.             st2.push(x);
  59.         }
  60.  
  61.         if(st2.isEmpty()){
  62.             System.out.println("Queue underflow.");
  63.         }
  64.         x = st2.pop();
  65.         while(!st2.isEmpty()){
  66.             x = st2.pop();
  67.             st1.push(x);
  68.         }
  69.  
  70.         return x;
  71.     }
  72. }
  73.  
  74. class Main {
  75.     public static void main(String[] args) {
  76.        
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment