-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue2_enqueue_dequeue_isFull_isEmpty
56 lines (50 loc) · 1.47 KB
/
queue2_enqueue_dequeue_isFull_isEmpty
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
public class Queue {
private LinkedList list;
// Queue constructor
public Queue()
{
// Create a new LinkedList.
list = new LinkedList();
}
public boolean isEmpty()
// Post: Returns true if the queue is empty. Otherwise, false.
{
return (list.size() == 0);
}
public void enqueue(Object item)
// Post: An item is added to the back of the queue.
{
// Append the item to the end of our linked list.
list.add(item);
}
public Object dequeue()
// Pre: this.isEmpty() == false
// Post: The item at the front of the queue is returned and
// deleted from the queue. Returns null if precondition
// not met.
{
// Store a reference to the item at the front of the queue
// so that it does not get garbage collected when we
// remove it from the list.
// Note: list.get(...) returns null if item not found at
// specified index. See postcondition.
Object item = list.get(1);
// Remove the item from the list.
// My implementation of the linked list is based on the
// J2SE API reference. In both, elements start at 1,
// unlike arrays which start at 0.
list.remove(1);
// Return the item
return item;
}
public Object peek()
// Pre: this.isEmpty() == false
// Post: The item at the front of the queue is returned and
// deleted from the queue. Returns null if precondition
// not met.
{
// This method is very similar to dequeue().
// See Queue.dequeue() for comments.
return list.get(1);
}
}