-
Notifications
You must be signed in to change notification settings - Fork 2
/
LinkedQueue1.java
66 lines (65 loc) · 1.81 KB
/
LinkedQueue1.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
package queue;
public class LinkedQueue1 {
//inv: size >= 0 ∧ ∀ i = 0..size - 1: a[i] ≠ null
private int size;
private Node tail = null;
private Node head = null;
// pre: element ≠ null
// post: size = size' + 1 ∧ ∀ i = 0..size' - 1 : a[i]' = a[i] ∧ a[size'] = element
public void enqueue(Object element) {
assert element != null;
Node temp = new Node(element, null);
if (isEmpty()) {
tail = temp;
} else {
head.next = temp;
}
head = temp;
head.next = null;
size++;
}
// pre: size > 0
// post: ℝ = tail.value ∧ size = size' − 1 ∧ ∀ i = 0..size - 1 : a[i]' = a[i]
public Object dequeue() {
assert size > 0;
size--;
Object result = tail.value;
if (tail.next == null) {
head = null;
}
tail = tail.next;
return result;
}
// pre: size > 0
// post: ℝ = tail.value ∧ size = size' ∧ ∀ i = 0..size - 1 : a[i]' = a[i]
public Object element() {
assert size > 0;
return tail.value;
}
// post: ℝ = size ∧ size = size' ∧ ∀ i = 0..size - 1 : a[i]' = a[i]
public int size() {
return size;
}
// post: ℝ = (size == 0) ∧ size = size' ∧ ∀ i = 0..size - 1 : a[i]' = a[i]
public boolean isEmpty() {
return size == 0;
}
// inv: value != null
private class Node {
private Object value;
private Node next;
public Node(Object value, Node next) {
assert value != null;
this.value = value;
this.next = next;
}
}
// pre: size > 0
// post: size = 0
public void clear() {
assert size > 0;
head = null;
tail = null;
size = 0;
}
}