Last active
January 9, 2021 11:10
-
-
Save alimranahmed/ba852cc4e012d379016a to your computer and use it in GitHub Desktop.
Queue-Data structure using Java(without using library)
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
/** | |
* 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; | |
} | |
} |
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
/** | |
* 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