-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedQueue.java
77 lines (64 loc) · 1.78 KB
/
LinkedQueue.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.NoSuchElementException;
class LinkedQueue {
private class Node {
String item;
Node next;
public Node(String s) {
item = s;
next = null;
}
}
private Node first;
private Node last;
private int size;
public LinkedQueue() {
first = null;
last = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return first == null;
}
public void enqueue(String s) {
Node temp = new Node(s);
if (isEmpty()) {
first = temp;
}
if (last != null) {
last.next = temp;
}
last = temp;
size++;
}
public String dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue underflow");
}
Node temp = first;
if (first == last) {
last = null;
}
first = first.next;
temp.next = null;
size--;
return temp.item;
}
public static void main(String[] args) {
String[] string = {"a", "b", "c", "d"};
LinkedQueue queue = new LinkedQueue();
System.out.println("isempty : " + queue.isEmpty() + ", size : " + queue.size());
for (String s : string) {
System.out.print("enqueue: " + s + " ");
queue.enqueue(s);
System.out.println("isempty : " + queue.isEmpty() + ", size : " + queue.size());
}
while(!queue.isEmpty()) {
System.out.print("Dequeue: " + queue.dequeue() + " ");
System.out.println("isempty : " + queue.isEmpty() + ", size : " + queue.size());
}
System.out.println("isempty : " + queue.isEmpty() + ", size : " + queue.size());
}
}