HamletPetrosyan

Untitled

Oct 27th, 2021
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 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 false;
  18.         }
  19.         return true;
  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 = new Stack(5);
  47.         st2 = new Stack(5);
  48.     }
  49.  
  50.     boolean isEmpty(){
  51.         return st1.isEmpty();
  52.     }
  53.  
  54.     void enqueue(int x){
  55.         st1.push(x);
  56.     }
  57.  
  58.     int dequeue(){
  59.         int x, ret;
  60.  
  61.         if(st1.isEmpty()){
  62.             System.out.println("Queue underflow.");
  63.             return 0;
  64.         }
  65.  
  66.         while(!st1.isEmpty()){
  67.             x = st1.pop();
  68.             st2.push(x);
  69.         }
  70.  
  71.         ret = st2.pop();
  72.  
  73.         while(!st2.isEmpty()){
  74.             x = st2.pop();
  75.             st1.push(x);
  76.         }
  77.  
  78.         return ret;
  79.     }
  80. }
  81.  
  82. class Main {
  83.     public static void main(String[] args) {
  84.         Queue a = new Queue();
  85.         a.enqueue(5);
  86.         a.enqueue(6);
  87.         a.enqueue(7);
  88.         a.dequeue();  
  89.         a.enqueue(10);
  90.         while(!a.isEmpty()){
  91.             System.out.print(a.dequeue() + " ");
  92.         }
  93.         System.out.print("\n");
  94.     }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment