Skip to content

Instantly share code, notes, and snippets.

@alexleventer
Created August 10, 2017 22:36
Show Gist options
  • Save alexleventer/d4db2b3b984c4eff9ed2216a5b8b6e1d to your computer and use it in GitHub Desktop.
Save alexleventer/d4db2b3b984c4eff9ed2216a5b8b6e1d to your computer and use it in GitHub Desktop.
public class LinkedListQueue<E> {
private class Node {
Node next;
E data;
public Node(E data, Node next) {
this.data = data;
this.next = next;
}
}
private Node head, tail;
public LinkedListQueue() {
head = null;
tail = null;
}
public boolean empty() {
return head == null;
}
public void enqueue(E element) {
if (tail != null) {
tail.next = new Node(element, null);
tail = tail.next;
} else {
tail = new Node(element, null);
head = tail;
}
}
public E dequeue() {
if (empty()) {
throw new IllegalStateException("Queue is empty");
}
E temp = head.data;
head = head.next;
return temp;
}
public E peek() {
if(empty()) {
throw new IllegalStateExceptio("Queue is empty");
} else {
return head.data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment