-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCustomQueue.java
More file actions
108 lines (74 loc) · 1.85 KB
/
CustomQueue.java
File metadata and controls
108 lines (74 loc) · 1.85 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* Implementation of queue
* enqueue
* dequeue
* */
import java.util.NoSuchElementException;
class Node<T> {
T value;
Node<T> next;
public Node(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
public class CustomQueue<T>{
private Node<T> first;
private Node<T> last;
private int n;
public CustomQueue() {
this.first = null;
this.last = null;
this.n = 0;
}
public boolean isEmpty() {
return this.first == null;
}
public void enqueue(T value) {
Node<T> oldLast = this.last;
this.last = new Node<T>(value);
this.last.next = null;
if(isEmpty()) {
this.first = this.last;
} else {
oldLast.next = this.last;
}
this.n++;
}
public int size() {
return this.n;
}
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue Underflow");
}
T value = this.first.getValue();
this.first = this.first.next;
this.n--;
if(isEmpty()) {
this.last = null;
}
return value;
}
public T peek() {
if(isEmpty()) {
throw new NoSuchElementException("Queue Underflow");
}
return this.first.getValue();
}
public static void main(String[] args) {
CustomQueue queue = new CustomQueue();
System.out.println(queue.isEmpty());
queue.enqueue(4);
queue.enqueue(3);
System.out.println(queue.peek());
System.out.println(queue.size());
queue.enqueue(2);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
}
}