Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import static java.lang.System.out;
- class QueueLab3Pt2 {
- public static void main(String[] args) {
- MyQueue2 q= new MyQueue2();
- Scanner console = new Scanner(System.in);
- int choice;
- int number;
- out.println(q);
- while (true) {
- out.println("Enter 1 to enqueue, 2 to dequeue, 3 to stop");
- choice = console.nextInt();
- switch (choice) {
- case 3: System.exit(0);
- case 1: out.println("Enter the number to enqueue");
- number = console.nextInt();
- q.add(number);
- q.display();
- break;
- case 2: out.println(q.remove() + " is dequeued");
- q.display();
- break;
- case 4:out.println(q.getSize());
- break;
- default: out.println("Invalid input");
- }
- }
- }
- }
- class MyQueue2{
- private int[] list;
- private int front;
- private int back;
- private int capacity;
- private int size;
- private boolean isFull()
- {
- if (back -1 == front)
- return true;
- else
- return false;
- }
- private void resize()
- {
- int oldCapacity = capacity;
- capacity *= 2;
- int[ ] newItems = new int[capacity];
- for (int i=0; i<size; i++) {
- newItems[i] = list[front++];
- if (front == oldCapacity)
- front = 0;
- }
- list = newItems;
- front = 0;
- back = size - 1;
- }
- public MyQueue2() {
- list=new int[4];
- back=-1;
- front=0;
- size=0;
- capacity=4;
- }
- public boolean isEmpty()
- {
- return (size==0);
- }
- public void add(int item)
- {
- if (size == capacity)
- resize();
- size++;
- back = (back + 1)%capacity;
- list[back] = item;
- }
- public int remove() {
- if (size == 0) {
- out.println("Queue is empty");
- return -999;
- }
- int answer = list[front++];
- size--;
- if (size == 0) {
- front = 0;
- back = -1;
- }
- if (front == capacity)
- front = 0;
- return answer;
- }
- public int peek()
- {
- if(size==0){out.println("Queue is empty");return -999;}
- return list[front];
- }
- public int getSize()
- {
- return size;
- }
- public void display()
- {
- out.println(toString());
- }
- public String toString() {
- if (size == 0)
- return "[ ]" ;
- String answer = "[ ";
- int position = front;
- for (int i=0; i<size; i++) {
- answer += list[position++] + " ";
- if (position == capacity) position = 0;
- }
- return answer + "] ";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement