不废话了,快憋不住了
- #include<iostream>
- using namespace std;
- typedef struct QNode{ //嗯,看来是个链队列FIFO,队尾进,队头出。队列节点的结构类型:当前数据+下一个数据的指针
- int data;
- struct QNode *next;
- }QNode,*QueuePtr;
- typedef struct{ //队列的数据结构,对头+对尾
- QueuePtr front; //front永远指向对头
- QueuePtr rear; //rear永远指向对尾
- }LinkQueue;
- void InitQueue(LinkQueue *queue); //初始化一个队列
- void InQueue(LinkQueue *queue, int data); //进队列
- void display(LinkQueue *queue); //打印队列
- int OutQueue(LinkQueue *queue); //出队列
- int main()
- {
- LinkQueue Q;
- int choice,OutElem,InData;
- InitQueue( &Q );
- cout << "0 to Insert----1 to Display-----2 to OutQueue----options to exit" << endl;
- cin >> choice;
- while(choice == 0 ||choice == 1 ||choice == 2)
- {
- switch(choice)
- {
- case 0:
- {
- cout << "Input element:" << endl;
- cin >> InData;
- InQueue(&Q,InData);
- cout << "Insert Successfully!" << endl;
- }
- break;
- case 1:
- {
- display(&Q);
- }
- break;
- case 2:
- {
- OutElem = OutQueue(&Q);
- cout << OutElem << endl;
- }
- break;
- default:
- exit(0);
- break;
- }
- cout << "Your choice:";
- cin >> choice;
- }
- return 0;
- }
- void InitQueue(LinkQueue *queue)
- {
- queue->front = queue->rear = (QueuePtr)malloc(sizeof(QNode)); //头尾分配空间,且此时头等于尾,即空队列
- if(!queue -> front)
- {
- cout << "Created failed!" << endl;
- exit(0);
- }
- else cout << "Created successfully!" << endl;
- queue->front->data = 0; //头节点数据域初始化为0,免得出现乱数,难看。
- queue->front->next = NULL; //头节点指针域置空
- }
- void InQueue(LinkQueue *queue,int data)
- {
- QueuePtr p; //新建一个队列节点
- p = (QueuePtr)malloc(sizeof(QNode));
- if(!queue -> front)
- exit(0);
- p->data = data;
- p->next = NULL;
- queue->rear->next = p; //*p链到原队尾结点后
- queue->rear = p; //队尾指针指向新的尾
- }
- void display(LinkQueue *queue)
- {
- LinkQueue p;
- p.front = queue->front;
- p.rear = queue->rear;
- if(queue->front == NULL&& queue->rear == NULL )
- {
- cout << "EMPTY!" << endl;
- //exit(0); //为了让while循环有意义
- }
- else
- while(queue -> front)
- {
- cout << queue->front->data << endl;
- queue->front = queue->front -> next;
- }
- queue->front = p.front;
- queue->rear = p.rear;
- }
- int OutQueue(LinkQueue *queue)
- {
- int temp;
- QueuePtr p;
- if(queue->front == NULL&& queue->rear == NULL)
- {
- cout << "Empty Queue!" << endl;
- return 0;
- }
- else
- {
- p = queue->front;
- temp = p->data; //把头节点后的第一个数据赋给temp
- queue->front = p->next;
- if(queue->rear == p)
- queue->rear = NULL;
- free(p);
- return temp;
- }
- }