使用两个双端队列实现,分别维护前半部分和后半部分 中间元素可放在任意一个deque中维护,这里使用前一个deque 提供两个调整成员函数,作用分别为使每个deque总为其代表的前(后)半部分,即总是使其deque为总的一半
class FrontMiddleBackQueue {
private : deque< int > front; deque< int > back;
public : FrontMiddleBackQueue ( ) { } void adjust_front ( ) { while ( front. size ( ) > back. size ( ) ) { int tmp = front. back ( ) ; front. pop_back ( ) ; back. push_front ( tmp) ; } } void adjust_back ( ) { while ( front. size ( ) < back. size ( ) ) { int t = back. front ( ) ; back. pop_front ( ) ; front. push_back ( t) ; } } void pushFront ( int val) { front. push_front ( val) ; adjust_front ( ) ; } void pushMiddle ( int val) { adjust_front ( ) ; front. push_back ( val) ; adjust_front ( ) ; } void pushBack ( int val) { back. push_back ( val) ; adjust_back ( ) ; } int popFront ( ) { adjust_back ( ) ; if ( front. empty ( ) ) return - 1 ; int tmp = front. front ( ) ; front. pop_front ( ) ; adjust_back ( ) ; return tmp; } int popMiddle ( ) { adjust_back ( ) ; if ( front. empty ( ) ) return - 1 ; int tmp = front. back ( ) ; front. pop_back ( ) ; adjust_back ( ) ; return tmp; } int popBack ( ) { adjust_front ( ) ; if ( back. empty ( ) ) return - 1 ; int tmp = back. back ( ) ; back. pop_back ( ) ; adjust_front ( ) ; return tmp; }
} ;