PTA 7-1 银行业务队列简单模拟
Posted fan-jiaming
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA 7-1 银行业务队列简单模拟相关的知识,希望对你有一定的参考价值。
用链表实现队列操作,代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <malloc.h> 5 6 using namespace std; 7 8 //函数状态码定义 9 #define TRUE 1 10 #define FALSE 0 11 #define OK 1 12 #define ERROR 0 13 #define INFEASIBLE -1 14 #define OVERFLOW -2 15 16 typedef int Status; 17 typedef int QElemType; 18 19 typedef struct QNode { 20 QElemType data; 21 struct QNode *next; 22 }QNode, *QueuePtr; 23 24 typedef struct { 25 QueuePtr front; 26 QueuePtr rear; 27 }LinkQueue; 28 29 Status InitQueue(LinkQueue &Q) { 30 Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode)); 31 if (!Q.front) exit(OVERFLOW); 32 Q.front->next = NULL; 33 return OK; 34 } 35 36 Status DestroyQueue(LinkQueue &Q) { 37 while (Q.front) { 38 cout << Q.front->data << endl; 39 Q.rear = Q.front->next; 40 free(Q.front); 41 Q.front = Q.rear; 42 } 43 return OK; 44 } 45 46 Status EnQueue(LinkQueue &Q, QElemType e) { 47 Q.rear->next = (QueuePtr)malloc(sizeof(QNode)); 48 if (!Q.rear->next) exit(OVERFLOW); 49 Q.rear->data = e; 50 Q.rear = Q.rear->next; 51 Q.rear->next = NULL; 52 return OK; 53 } 54 55 Status DeQueue(LinkQueue &Q, QElemType &e) { 56 if (Q.front == Q.rear) 57 return ERROR; 58 e = Q.front->data; 59 QueuePtr p = Q.front; 60 Q.front = Q.front->next; 61 free(p); 62 return OK; 63 } 64 65 bool EmptyQueue(LinkQueue &Q) { 66 return Q.front == Q.rear; 67 } 68 69 int main() 70 { 71 LinkQueue A, B; 72 InitQueue(A); 73 InitQueue(B); 74 int n, m; 75 cin >> n; 76 for (int i = 0; i < n; ++i) { 77 cin >> m; 78 if (m & 1) 79 EnQueue(A, m); 80 else 81 EnQueue(B, m); 82 } 83 bool ok = false; 84 while (!EmptyQueue(A) && !EmptyQueue(B)) { 85 DeQueue(A, m); 86 if (ok) 87 cout << ‘ ‘ << m; 88 else 89 cout << m; 90 91 if (!EmptyQueue(A)) { 92 DeQueue(A, m); 93 cout << ‘ ‘ << m; 94 } 95 DeQueue(B, m); 96 cout << ‘ ‘ << m; 97 ok = true; 98 } 99 while (!EmptyQueue(A)) { 100 DeQueue(A, m); 101 if (ok) 102 cout << ‘ ‘ << m; 103 else 104 cout << m; 105 ok = true; 106 } 107 while (!EmptyQueue(B)) { 108 DeQueue(B, m); 109 if (ok) 110 cout << ‘ ‘ << m; 111 else 112 cout << m; 113 ok = true; 114 } 115 return 0; 116 }
以上是关于PTA 7-1 银行业务队列简单模拟的主要内容,如果未能解决你的问题,请参考以下文章