-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.java
More file actions
59 lines (51 loc) · 1.1 KB
/
queue.java
File metadata and controls
59 lines (51 loc) · 1.1 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
import java.util.*;
class Queue<E>{
private class Element<E>{
private E data;
private Element<E> next;
Element(E data){
this.data = data;
this.next = null;
}
}
private Element<E> front;
private Element<E> back;
public Queue(){
this.front = null;
this.back = null;
}
public boolean isEmpty(){
return front == null || back == null;
}
public void enqueue(E value){
Element<E> newElement = new Element<E>(value);
if(this.isEmpty()){
this.front = newElement;
}
else{
this.back.next = newElement;
}
this.back = newElement;
}
public E dequeue(){
if(isEmpty()){
throw new NoSuchElementException();
}
Element<E> head = front;
this.front = front.next;
return head.data;
}
public E peekFirst(){
if(isEmpty()){
throw new NoSuchElementException();
}
return this.front.data;
}
public E peekLast(){
if(this.isEmpty()){
throw new NoSuchElementException();
}
return this.back.data;
}
}
}