Skip to content

Solution for Queue #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: exercises/dsa/queue
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/main/java/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ public class Node<T> {
public Node<T> next;

public Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
}
35 changes: 35 additions & 0 deletions src/main/java/Queue.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,49 @@ public class Queue<T> {
public Node<T> tail;

public Queue() {
length = 0;
head = null;
tail = null;
}

public void enqueue(T item) {
if (item == null) {
return;
}
length++;
final Node<T> node = new Node<T>(item, null);
if (this.length == 1) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}

public T deque() {
if (length == 0) {
return null;
} else if (length == 1) {
length--;
Node<T> tmp = head;
tmp.next = null;
head = null;
tail = null;
return tmp.value;
} else {
length--;
Node<T> tmp = head;
head = head.next;
tmp.next = null;
return tmp.value;
}
}

public T peek() {
if (head != null) {
return head.value;
}
return null;
}
}