Advertisement
Guest User

arraystackqueue

a guest
Mar 26th, 2024
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | Source Code | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class ArrayStackQueue<T> {
  4.     T[] asq;
  5.     int m;
  6.     int top, front, rear;
  7.  
  8.     @SuppressWarnings("unchecked")
  9.     public ArrayStackQueue(int m) {
  10.         asq = (T[]) new Object[2 * m];
  11.  
  12.         this.m = m;
  13.         top = -1;
  14.         front = 2 * m;
  15.         rear = 2 * m;
  16.  
  17.         for (int i = 0; i < asq.length; i++)
  18.             asq[i] = null;
  19.     }
  20.  
  21.     public void push(T element) {
  22.         if (top == m - 1)
  23.             throw new IllegalArgumentException("Stack is full!");
  24.  
  25.         asq[++top] = element;
  26.     }
  27.  
  28.     public void insert(T element) {
  29.         if (rear == m)
  30.             throw new IllegalArgumentException("Queue is full!");
  31.  
  32.         if (rear == 2 * m) {
  33.             front = 2 * m - 1;
  34.         }
  35.  
  36.         rear--;
  37.         asq[rear] = element;
  38.     }
  39.  
  40.     public T remove() {
  41.         if (rear == 2 * m)
  42.             throw new IllegalArgumentException("Queue is Empty");
  43.  
  44.         T x = asq[front];
  45.         asq[front] = null;
  46.         if (front == rear) {
  47.             front = 2 * m;
  48.             rear = 2 * m;
  49.         } else {
  50.             front = front - 1;
  51.         }
  52.         return x;
  53.     }
  54.  
  55.     public static void main(String[] args) {
  56.         ArrayStackQueue<Integer> asq = new ArrayStackQueue<>(3);
  57.         asq.push(10);
  58.         asq.push(20);
  59.         asq.push(30);
  60.         System.out.println(Arrays.toString(asq.asq));
  61.         asq.insert(90);
  62.         asq.insert(100);
  63.         asq.insert(120);
  64.         System.out.println(Arrays.toString(asq.asq));
  65.         asq.remove();
  66.         asq.remove();
  67.         asq.remove();
  68.         System.out.println(Arrays.toString(asq.asq));
  69.  
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement