Skip to content

Instantly share code, notes, and snippets.

@so77id
Created September 4, 2020 19:58
Show Gist options
  • Save so77id/9ca906efa7139d215a6dfc9ef0d7f0e3 to your computer and use it in GitHub Desktop.
Save so77id/9ca906efa7139d215a6dfc9ef0d7f0e3 to your computer and use it in GitHub Desktop.
Queue in java generic
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args){
int n;
int buff;
Scanner scanner = new Scanner(System.in); // Create a Scanner object
Queue<Integer> myQueue = new Queue<Integer>();
System.out.println("Ingrese la cantidad de datos que va a adicionar a la cola");
n = scanner.nextInt();
for(int i=0; i < n; i++){
buff = scanner.nextInt();
myQueue.enqueue(buff);
}
while(!myQueue.empty()){
buff = myQueue.top();
myQueue.dequeue();
System.out.println(buff);
}
// int n;
// String buff;
// Scanner scanner = new Scanner(System.in); // Create a Scanner object
//
// Queue<String> myQueue = new Queue<String>();
// System.out.println("Ingrese la cantidad de datos que va a adicionar a la cola");
// n = scanner.nextInt();
//
// for(int i=0; i < n; i++){
// buff = scanner.next();
// myQueue.enqueue(buff);
// }
//
// while(!myQueue.empty()){
// buff = myQueue.top();
// myQueue.dequeue();
// System.out.println(buff);
// }
}
}
class Node<T extends Comparable<T>> {
private T value;
private Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public Node(T value) {
this.value = value;
this.next = null;
}
public Node() {
this.value = null;
this.next = null;
}
public T getValue() { return this.value; }
public Node getNext() { return this.next; }
public void setValue(T value) { this.value = value; }
public void setNext(Node next) { this.next = next; }
}
class Queue<T extends Comparable<T>> {
private Node<T> head;
private Node<T> tail;
public Queue() {
this.head = this.tail = null;
}
public void enqueue(T value){
Node n_node = new Node(value);
// no elements
if(this.head == null && this.tail == null) {
this.head = this.tail = n_node;
}
else {
// 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 T top(){
return this.head.getValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment