-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLinkedQueue.java
More file actions
44 lines (38 loc) · 917 Bytes
/
LinkedQueue.java
File metadata and controls
44 lines (38 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.github.andavid.ds.datastructure.queue;
import com.github.andavid.ds.datastructure.linkedlist.ListNode;
public class LinkedQueue {
ListNode head;
ListNode tail;
public void enqueue(int value) {
ListNode newNode = new ListNode(value);
if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public int dequeue() {
if (head == null) {
throw new IllegalArgumentException("queue empty");
}
int value = head.val;
head = head.next;
if (head == null) {
tail = null;
}
return value;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (ListNode p = head; p != null; p = p.next) {
sb.append(p.val);
if (p.next != null) {
sb.append(",").append(" ");
}
}
sb.append("]");
return sb.toString();
}
}