Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ArrayStackQueue<T> {
- T[] asq;
- int m;
- int top, front, rear;
- @SuppressWarnings("unchecked")
- public ArrayStackQueue(int m) {
- asq = (T[]) new Object[2 * m];
- this.m = m;
- top = -1;
- front = 2 * m;
- rear = 2 * m;
- for (int i = 0; i < asq.length; i++)
- asq[i] = null;
- }
- public void push(T element) {
- if (top == m - 1)
- throw new IllegalArgumentException("Stack is full!");
- asq[++top] = element;
- }
- public void insert(T element) {
- if (rear == m)
- throw new IllegalArgumentException("Queue is full!");
- if (rear == 2 * m) {
- front = 2 * m - 1;
- }
- rear--;
- asq[rear] = element;
- }
- public T remove() {
- if (rear == 2 * m)
- throw new IllegalArgumentException("Queue is Empty");
- T x = asq[front];
- asq[front] = null;
- if (front == rear) {
- front = 2 * m;
- rear = 2 * m;
- } else {
- front = front - 1;
- }
- return x;
- }
- public static void main(String[] args) {
- ArrayStackQueue<Integer> asq = new ArrayStackQueue<>(3);
- asq.push(10);
- asq.push(20);
- asq.push(30);
- System.out.println(Arrays.toString(asq.asq));
- asq.insert(90);
- asq.insert(100);
- asq.insert(120);
- System.out.println(Arrays.toString(asq.asq));
- asq.remove();
- asq.remove();
- asq.remove();
- System.out.println(Arrays.toString(asq.asq));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement