Created
March 31, 2020 06:05
-
-
Save so77id/bee85582341d64fb95bd53a2bf6b0218 to your computer and use it in GitHub Desktop.
Example of queue implemented over linked list in java
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; // 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()); | |
} | |
} | |
} |
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
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; } | |
} |
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
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