/**
* 双端队列
* @author gzn
* @version 1.0
*/
public
class
Deque<E>{
private
E[] data;
private
int
front, tail;
private
int
size;
public
Deque(
int
capacity){
data = (E[])
new
Object[capacity];
front = tail =
0
;
size =
0
;
}
public
int
getCapacity(){
return
data.length;
}
public
int
getSize(){
return
size;
}
public
boolean
isEmpty(){
return
size ==
0
;
};
private
void
resize(
int
newCapacity){
E[] newData = (E[])
new
Object[newCapacity];
for
(
int
i =
0
; i < size; i ++){
newData[i] = data[(i + front) % data.length];
}
data = newData;
front =
0
;
tail = size -
1
;
}
public
void
addFront(E e){
if
(size == getCapacity()){
resize(getCapacity() *
2
);
}
if
(data[front] !=
null
){
front = front ==
0
? data.length -
1
: front -
1
;
}
data[front] = e;
size ++;
}
public
void
addLast(E e){
if
(size == getCapacity()){
resize(getCapacity() *
2
);
}
if
(data[tail] !=
null
){
tail = (tail +
1
) % getCapacity();
}
data[tail] = e;
size ++;
}
public
E removeFront(){
if
(isEmpty()){
throw
new
RuntimeException(
"RemoveFront failed. Cannot remove from a empty deque."
);
}
E ret = data[front];
data[front] =
null
;
size --;
if
(!isEmpty()){
front = (front +
1
) % data.length;
}
if
(size == getCapacity() /
4
&& getCapacity() /
2
!=
0
){
resize(getCapacity() /
2
);
}
return
ret;
}
public
E removeLast(){
if
(isEmpty()){
throw
new
RuntimeException(
"RemoveLast failed. Cannot remove from a empty deque."
);
}
E ret = data[tail];
data[tail] =
null
;
size --;
if
(!isEmpty()){
tail = tail ==
0
? data.length -
1
: tail -
1
;
}
if
(size == getCapacity() /
4
&& getCapacity() /
2
!=
0
){
resize(getCapacity() /
2
);
}
return
ret;
};
public
E getFront(){
if
(isEmpty()){
throw
new
RuntimeException(
"Deque si empty."
);
}
return
data[front];
}
public
E getLast(){
if
(isEmpty()){
throw
new
RuntimeException(
"Deque si empty."
);
}
return
data[tail];
}
@Override
public
String toString(){
StringBuilder res =
new
StringBuilder();
res.append(String.format(
"Dedeque: size = %d, capacity = %d\n"
, size, data.length));
res.append(
"front ["
);
for
(
int
i =
0
; i < size ; i ++){
res.append(data[(i + front) % data.length]);
if
(i != size -
1
){
res.append(
" ,"
);
}
}
res.append(
"] tail"
);
return
res.toString();
}
public
static
void
main(String[] args) {
Deque<Integer> deque =
new
Deque<>(
10
);
for
(
int
i =
0
; i <
10
; i ++){
if
(i %
2
==
0
){
deque.addLast(i);
System.out.println(deque);
System.out.println(
"当前添加元素:"
+ deque.getLast());
}
else
{
deque.addFront(i);
System.out.println(deque);
System.out.println(
"当前添加元素: "
+ deque.getFront());
}
if
(i %
3
==
2
){
if
(i %
2
==
0
){
deque.removeLast();
System.out.println(deque);
}
else
{
deque.removeFront();
System.out.println(deque);
}
}
}
}
}
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧