Queues

Run Settings
LanguageJava
Language Version
Run Command
import java.util.Stack; class Queue{ private Stack<String> stack=null; private String firstElement=null; public Queue(){ stack = new Stack<String>(); } public boolean enqueue(String value){ if (value == null || value.isEmpty()){ System.out.println("The value to enqueue cannot be null or empty."); return false; } if (firstElement == null){ firstElement= value; } stack.push(value); return true; } public String dequeue(){ if (stack.isEmpty()){ System.out.println("CAnnot dequeue, the queue is empty."); } Stack<String> temporalReversedStack= new Stack<String>(); while (!stack.isEmpty()){ temporalReversedStack.push(stack.pop()); } String removedValue = temporalReversedStack.pop(); firstElement = temporalReversedStack.peek(); while (!temporalReversedStack.isEmpty()){ stack.push(temporalReversedStack.pop()); } return removedValue; } public String peek(){ if (stack.isEmpty()){ System.out.println("The queue is empty."); return null; } return firstElement; } } class Main { public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue("1"); queue.enqueue("2"); queue.enqueue("3"); queue.dequeue(); System.out.println("Peek:"+ queue.peek()); } }
Editor Settings
Theme
Key bindings
Full width
Lines