Skip to content

Instantly share code, notes, and snippets.

@so77id
Created March 31, 2020 06:05
Show Gist options
  • Save so77id/bee85582341d64fb95bd53a2bf6b0218 to your computer and use it in GitHub Desktop.
Save so77id/bee85582341d64fb95bd53a2bf6b0218 to your computer and use it in GitHub Desktop.
Example of queue implemented over linked list in java
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args){
int n, buff;
Node tmp;
Scanner scanner = new Scanner(System.in); // Create a Scanner object
Queue myQueue = new Queue();
n = scanner.nextInt();
for(int i=0; i < n; i++){
buff = scanner.nextInt();
myQueue.enqueue(buff);
}
while(!myQueue.empty()){
tmp = myQueue.top();
myQueue.dequeue();
System.out.println(tmp.getValue());
}
}
}
class Node {
private int value;
private Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node(int value) {
this.value = value;
this.next = null;
}
public int getValue() { return (this.value); }
public void setValue(int value) { this.value = value; }
public Node getNext() { return (this.next); }
public void setNext(Node next) { this.next = next; }
}
class Queue {
private Node head;
private Node tail;
public Queue() {
this.head = this.tail = null;
}
public void enqueue(int value){
Node n_node = new Node(value);
// no elements
if(this.head == null && this.tail == null) {
this.head = this.tail = n_node;
}
// n elements
this.tail.setNext(n_node);
this.tail = n_node;
}
public void dequeue() {
// no elements
if(this.head == null && this.tail == null) return;
// 1 element
if(this.head == this.tail) {
this.head = this.tail = null;
return;
}
// n elements
this.head = this.head.getNext();
}
public boolean empty(){
if (this.head == null) return true;
else return false;
}
public Node top(){
Node tmp = this.head;
return tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment