算法 辅助栈 核心思想 一个栈负责尾端进出,一个栈负责头端进出,由于两个栈相互转存,必然颠倒顺序,剩下的就很简单了。千万不要像我智障般的玩了半天双队列。计数部分使用了一个全局变量。 代码
class MyCircularDeque {
Stack< Integer> qu1;
Stack< Integer> qu2;
int k;
int num = 0 ;
public MyCircularDeque ( int k) {
qu1 = new Stack < Integer> ( ) ;
qu2 = new Stack < Integer> ( ) ;
this . k = k;
}
public boolean insertFront ( int value) {
if ( num < k) {
transform ( qu1, qu2) ;
qu2. push ( value) ;
num++ ;
return true ;
} else return false ;
}
public boolean insertLast ( int value) {
if ( num < k) {
transform ( qu2, qu1) ;
qu1. push ( value) ;
num++ ;
return true ;
} else return false ;
}
public boolean deleteFront ( ) {
transform ( qu1, qu2) ;
if ( num == 0 ) return false ;
else {
qu2. pop ( ) ;
num-- ;
return true ;
}
}
public boolean deleteLast ( ) {
transform ( qu2, qu1) ;
if ( num == 0 ) return false ;
else {
qu1. pop ( ) ;
num-- ;
return true ;
}
}
public int getFront ( ) {
transform ( qu1, qu2) ;
if ( qu2. isEmpty ( ) ) return - 1 ;
else {
return qu2. peek ( ) ;
}
}
public int getRear ( ) {
transform ( qu2, qu1) ;
if ( qu1. isEmpty ( ) ) return - 1 ;
else {
return qu1. peek ( ) ;
}
}
public boolean isEmpty ( ) {
if ( qu1. isEmpty ( ) && qu2. isEmpty ( ) ) return true ;
else return false ;
}
public boolean isFull ( ) {
if ( num == k) return true ;
else return false ;
}
public void transform ( Stack< Integer> qu1, Stack< Integer> qu2) {
while ( ! qu1. isEmpty ( ) ) {
qu2. push ( qu1. pop ( ) ) ;
}
}
}