- 假設以帶頭節點的循環鏈表表示隊列,並且只設一個指針指向隊尾元素節點(不設頭指針),節點元素這里設為整型,編寫隊列的初始化、入隊和出隊算法。其中入隊元素個數n及其節點數據,和出隊元素個數m都是從鍵盤輸入(默認n、m都不小於0),然后輸出出隊元素,出隊不合法(自己想想什么情況下不合法)則輸出Error。
要求:能進行多次的入隊、出隊操作。無元素入隊時,n=0;無元素出隊時m=0。m=0 n=0時,算法結束。
提示:元素出隊時的相應各種情況的處理。
-2 0 1 7 10 -1
2 3
4 3
7 10 -1
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; }