Queues

Run Settings
LanguageJava
Language Version
Run Command
class Node{ private String value = null; private Node next=null; public Node(String value){ this.value= value; } public void setValue(String value){ this.value = value; } public String getValue(){ return this.value; } public void setNext(Node next){ this.next = next; } public Node getNext(){ return this.next; } } class Queue{ private Node firstElement= null; private Node lastElement = null; private int length= 0; public Queue(){ } public String peek(){ if (this.length ==0){ System.out.println("The queue is empty, not value to peek."); return null; } return this.firstElement.getValue(); } public void enqueue(String value){ Node newElement = new Node(value); if (firstElement == null){ firstElement = newElement; } if (lastElement == null){ lastElement = newElement; } else { lastElement.setNext(newElement); lastElement= newElement; } this.length++; } public String dequeue(){ if (this.length == 0){ System.out.println("The queue is empty, no value can be dequeued."); return null; } Node dequeuedElement = firstElement; firstElement = firstElement.getNext(); this.length--; return dequeuedElement.getValue(); } public void printAll(){ if (this.length == 0){ System.out.println("The queue is empty, no values can be printed."); return; } Node currentElement = firstElement; while (currentElement != null){ System.out.println(currentElement.getValue()); currentElement = currentElement.getNext(); } } } class Main { public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue("1"); System.out.println("Peek: "+ queue.peek()); queue.enqueue("2"); queue.enqueue("3"); queue.printAll(); System.out.println("Peek: "+ queue.peek()); queue.dequeue(); System.out.println("Peek: "+ queue.peek()); queue.enqueue("4"); } }
Editor Settings
Theme
Key bindings
Full width
Lines