实验目标:
(1)初始化链队列为空队列
(2)新元素e入队列,成功返回true,失败返回false
(3)出队列,即删除队首元素,并用e返回出元素值,成功返回true,失败返回false
(4)读队首元素,用e返回队首元素,不出队,成功返回true,失败返回false
(5)遍历链队列,将队列数据元素依次输出
(6)销毁链队列
据我发现,所谓队列先进先出,和链表的尾插法类似之处
实验代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| #include <bits/stdc++.h>> using namespace std;
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2
typedef int Status; typedef int QElemType;
typedef struct QNode{ QElemType data; struct QNode *next; }QNode,*Queue;
typedef struct{ Queue front; Queue rear; }LinkQueue;
Status InitQueue (LinkQueue &Q) { Q.front=Q.rear=(Queue)malloc(sizeof(QNode)); if(!Q.front) exit(OVERFLOW); Q.front->next=NULL;
cout<<endl; return OK; }
Status EnQueue (LinkQueue &Q, QElemType e) { struct QNode* newNode=(Queue)malloc(sizeof(QNode)); if(!newNode) exit(OVERFLOW); newNode->data=e; newNode->next=NULL; Q.rear->next=newNode; Q.rear=newNode; return OK; }
Status DeQueue (LinkQueue &Q, QElemType &e) { struct QNode* p=(Queue)malloc(sizeof(QNode)); if(Q.front==Q.rear) return ERROR; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p) Q.rear=Q.front; free(p); return e; }
Status GetHead(LinkQueue &Q) { if(Q.front==Q.rear) return FALSE; struct QNode* posNode=(Queue)malloc(sizeof(QNode)); posNode=Q.front->next; cout<<posNode->data<<endl; return OK; }
Status Traverse(LinkQueue &Q) { if(Q.front==Q.rear) return FALSE; struct QNode* posNode=Q.front->next; while(posNode!=NULL){ cout<<posNode->data<<" "; posNode=posNode->next; } cout<<endl; return OK; }
Status Destroy(LinkQueue &Q) { if(Q.front==Q.rear) return FALSE; while(Q.front){ Q.rear=Q.front->next; free(Q.front); Q.front=Q.rear; } cout<<endl; return OK; }
int main() { LinkQueue Q; int e;
while(1){ cout<<endl; cout<<"**1,初始化队列"<<endl; cout<<"**2,将元素e入列"<<endl; cout<<"**3,出队列,用e返回出队列元素"<<endl; cout<<"**4,返回列首元素"<<endl; cout<<"**5,遍历队列"<<endl; cout<<"**6,销毁队列"<<endl; cout<<"**0,退出系统"<<endl<<endl;
int choice; cout<<"请输入要进行的操作:"; cin>>choice; cout<<endl;
switch(choice){ case 1:InitQueue(Q);break; case 2:{ int n; cout<<"请输入本次入队的元素个数:"; cin>>n;
cout<<endl<<"请输入要插入的元素:"; for(int i=1;i<=n;i++){ cin>>e; EnQueue(Q,e); } cout<<"入栈成功!"<<endl; break; } case 3:{ DeQueue(Q,e); cout<<"出队成功!"<<endl; break; } case 4:GetHead(Q);break; case 5:Traverse(Q);break; case 6:Destroy(Q);break; case 0:exit(0); } }
system("pause"); return 0; }
|