Created
August 27, 2022 12:14
-
-
Save z1nc0r3/20fad2b938db992a2108fe5b033ba037 to your computer and use it in GitHub Desktop.
Queue using string array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Queue { | |
public int size; | |
public int front = 0; | |
public int rear = -1; | |
public String[] queue; | |
Queue(int size) { | |
this.size = size; | |
queue = new String[size]; | |
} | |
public void enQueue(String data) { | |
if (!isFull()) { | |
queue[++rear] = data; | |
} else { | |
System.out.println("Queue is full."); | |
} | |
} | |
public void deQueue() { | |
if (isEmpty()) { | |
System.out.println("Queue is empty"); | |
return; | |
} | |
for (int i=0; i<rear; i++) { | |
queue[i] = queue[i + 1]; | |
} | |
queue[rear--] = null; | |
} | |
public void print() { | |
if (isEmpty()) { | |
System.out.println("Queue is empty."); | |
return; | |
} | |
for (int i = front; i <= rear; i++) { | |
System.out.print(queue[i] + " "); | |
} | |
System.out.println(); | |
} | |
public void peek() { | |
System.out.println(queue[front]); | |
} | |
public boolean isEmpty() { | |
return (rear < front); | |
} | |
public boolean isFull() { | |
return (rear == size - 1); | |
} | |
public static void main(String[] args) { | |
Scanner read = new Scanner(System.in); | |
Queue myQ = new Queue(5); | |
myQ.deQueue(); | |
for (int i=0; i<5; i++) { | |
myQ.enQueue(read.nextLine()); | |
} | |
myQ.peek(); | |
myQ.print(); | |
myQ.deQueue(); | |
myQ.print(); | |
for (int i=0; i<5; i++) { | |
myQ.deQueue(); | |
} | |
myQ.enQueue("hello"); | |
myQ.enQueue("world"); | |
myQ.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment