要求:能進行屢次的入隊、出隊操做。無元素入隊時,n=0;無元素出隊時m=0。m=0 n=0時,算法結束。c++
提示:元素出隊時的相應各類狀況的處理。算法
6 4 0 3 1 21 9 -1 2 3 5 6 0 0
0 3 1 21 9 -1 5
#include<bits/stdc++.h> using namespace std; template<class T> struct Node { T data; Node<T> *next; }; template<class T> class LinkQueue { private: int length; Node<T> *front,*rear; public: LinkQueue(); ~LinkQueue(); void Insert_Queue(T x); T Delete_Queue(); int Get_Length(){return length;} }; /* 構造隊列 */ template<class T> LinkQueue<T>::LinkQueue() { front=new Node<T>; front->next=NULL; rear=front; length=0; } /* 析構 */ template<class T> LinkQueue<T>::~LinkQueue() { Node<T> *p; while(front) { p=front->next; front=front->next; delete p; } } /* 入隊 */ template<class T> void LinkQueue<T>::Insert_Queue(T x) { Node<T>*s; s=new Node<T>; s->data=x; s->next=NULL; rear->next=s; rear=s; length++; } /* 出隊 */ template<class T> T LinkQueue<T>::Delete_Queue() { if(rear==front) throw "Error"; Node<T> *p; p=front->next; T x=p->data; front->next=p->next; delete p; if(front->next==NULL) rear=front;///刪除只有一個元素的時候 length--; return x; } int main() { int n,m,x; LinkQueue<int> My_queue; while(scanf("%d%d",&n,&m)) { if(n==0&&m==0) break; for(int i=1;i<=n;i++) { scanf("%d",&x); My_queue.Insert_Queue(x); } if(m>My_queue.Get_Length()) { printf("Error\n"); } else { for(int i=1;i<=m;i++) { if(i==m) { printf("%d\n",My_queue.Delete_Queue()); } else { printf("%d ",My_queue.Delete_Queue()); } } } } My_queue.~LinkQueue(); return 0; }