Skip to content

Instantly share code, notes, and snippets.

@alimranahmed
Last active January 9, 2021 11:10
Show Gist options
  • Save alimranahmed/ba852cc4e012d379016a to your computer and use it in GitHub Desktop.
Save alimranahmed/ba852cc4e012d379016a to your computer and use it in GitHub Desktop.
Queue-Data structure using Java(without using library)
/**
* Implementation of Queue using Java
* @author Al- Imran Ahmed
*/
public class Queue<T>{
Node font = null;
Node back = null;
private class Node{
T item;
Node next;
}
/**
* Remove an element from the end of the queue
* @return T
* public T dequeue(){ return null; } ;stub
*/
public T dequeue(){
if(isEmpty()){
return null;
}
T item = font.item;
if(font == back){
back = back.next;
}
font = font.next;
return item;
}
/**
* Insert an element at the beginning of the queue
* @param T
* public void enqueue(T item){ } ; stub;
*/
public void enqueue(T item){
Node oldback = back;
back = new Node();
back.item = item;
if(isEmpty()){
font = back;
}else{
oldback.next = back;
}
}
/**
* Check whether the queue is empty or not
* @return boolean
* public boolean isEmpty(){ return false; } ;stub
*/
public boolean isEmpty(){
return font == null;
}
}
/**
* Client to Test Queue.java
* @author Al- Imran Ahmed
* Enqueue each value but dequeue when '-' entered
* java Client < input.txt
*/
import java.util.Scanner;
public class Client{
//Client method
public static void main(String[] CHAND){
//Create an instance of stack
Queue<String> queue = new Queue<String>();
Scanner input = new Scanner(System.in);
String s;
System.out.println("Output: ");
while(input.hasNext()){
s = input.next();
if(s.equals("-")){
System.out.print(queue.dequeue()+" ");
}else{
queue.enqueue(s);
}
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment