Created
May 24, 2015 21:59
-
-
Save rootid/c6b3f7de8ab5038663bf to your computer and use it in GitHub Desktop.
This file contains hidden or 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<T> { | |
//Queue using DLL | |
class Node { | |
T data; | |
Node prev; | |
Node next; | |
Node (T data) { | |
this.data = data; | |
this.next = null; | |
this.prev = null; | |
} | |
} | |
private Node front; | |
private Node back; | |
//Intialization | |
Queue () { | |
this.front = null; | |
this.back = null; | |
} | |
//Add/Insert the data into a queue | |
public void offer (T data) { | |
Node tmp = new Node (data); | |
if (this.front == null) { | |
this.front = tmp; | |
this.back = this.front; | |
} else { | |
tmp.next = this.front; | |
this.front.prev = tmp; | |
this.front = tmp; | |
} | |
} | |
//Remove the data from a queue | |
public T poll() { | |
if (!isEmpty()) { | |
Node tmp = this.back; | |
T tmpData = (T)tmp.data; | |
if (this.back == this.front) { | |
this.back = null; | |
this.front = null; | |
} else { | |
this.back = tmp.prev; | |
tmp = null; | |
} | |
return tmpData ; | |
} | |
return null; | |
} | |
//Get the data from queue | |
public T peek() { | |
if (!isEmpty()) { | |
T tmpData = (T) this.back.data; | |
return tmpData; | |
} | |
return null; | |
} | |
public boolean isEmpty() { | |
if (front == null && back == null) { | |
return true; | |
} | |
return false; | |
} | |
public static void main(String[] args) { | |
Queue<String> tQ = new Queue<String> (); | |
tQ.offer("Hi"); | |
tQ.offer("Hello"); | |
tQ.offer("Bye"); | |
System.out.println(tQ.peek()); | |
tQ.poll(); | |
System.out.println(tQ.peek()); | |
tQ.poll(); | |
System.out.println(tQ.peek()); | |
tQ.poll(); | |
System.out.println(tQ.peek()); | |
tQ.offer("Bye"); | |
System.out.println(tQ.peek()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment