-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deque.java
77 lines (77 loc) · 1.19 KB
/
Deque.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
public class Deque<T>{
private int N;
private DNode first, last;
private class DNode{
T item;
DNode prev, next;
DNode(T item){
this.item = item;
}
}
public boolean isEmpty(){
return N == 0;
}
public int size(){
return N;
}
public void pushLeft(T item){
if(N == 0){
first = new DNode(item);
last = first;
}
else{
DNode newFirst = new DNode(item);
first.prev = newFirst;
newFirst.next = first;
first = newFirst;
}
N++;
}
public void pushRight(T item){
if(N == 0){
last = new DNode(item);
first = last;
}
else{
DNode newLast = new DNode(item);
last.next = newLast;
newLast.prev = last;
last = newLast;
}
N++;
}
public T popLeft(){
T ret = null;
if(N == 1){
ret = first.item;
first = last = null;
}
else if (N > 1){
ret = first.item;
first = first.next;
first.prev = null;
}
else{
throw new IllegalStateException();
}
N--;
return ret;
}
public T popRight(){
T ret = null;
if(N == 1){
ret = last.item;
first = last = null;
}
else if(N > 1){
ret = last.item;
last = last.prev;
last.next = null;
}
else{
throw new IllegalStateException();
}
N--;
return ret;
}
}