双端队列
很简单,直接贴代码
//抽象数据类型表示 class Deque { public: Deque(int sz) { size=sz; front=0; rear=0; data=new int[size]; for(int i=0;i<10;i++) data[i]=0; } bool EnQueueTail(int x); int DeQueueHead(); bool EnQueueHead(int x); int DeQueueTail(); void Output(); private: int front,rear; int *data; int size; }; /*在队尾入队,队头出队*/ bool Deque::EnQueueTail(int x) { if(rear!=size-1) { data[rear]=x; rear++; return true; } else { cout<<"队列已满"<<endl; return false; } } int Deque::DeQueueHead() { int x=data[front]; front++; return x; } /* 在队头入队,队尾出队 */ bool Deque::EnQueueHead(int x) { front=(front-1+size)%size; data[front]=x; return true; } int Deque::DeQueueTail() { int x; if(front==rear) return false; rear=(rear-1+size)%size; x=data[rear]; return x; } void Deque::Output() { for(int i=0;i<size;i++) cout<<data[i]<<" "; cout<<endl; }
主程序:
int _tmain(int argc, _TCHAR* argv[]) { cout<<"----------双端队列---------"<<endl; Deque dq(10); //队头出队,队尾入队 dq.EnQueueTail(1); dq.EnQueueTail(2); dq.EnQueueTail(3); dq.EnQueueTail(4); dq.Output(); cout<<"队头出队:"<<dq.DeQueueHead()<<endl; cout<<"队头出队:"<<dq.DeQueueHead()<<endl; dq.Output(); //队尾出队,队头入队 dq.EnQueueHead(100); dq.EnQueueHead(200); dq.EnQueueHead(300); dq.EnQueueHead(400); dq.Output(); cout<<"队尾出队"<<dq.DeQueueTail()<<endl; cout<<"队尾出队"<<dq.DeQueueTail()<<endl; dq.Output(); return 0; }