Catalog
队列的实现
#include<iostream>
using namespace std;
typedef int QElemType;
typedef struct QNode {
QElemType data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;

QueuePtr InitQueue(LinkQueue &Q) {
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
Q.front->next = NULL;
return Q.front;
}
bool DestroyQueue(LinkQueue& Q) {
while (Q.front) {
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return 1;
}

bool EnQueue(LinkQueue &Q, QElemType e) {
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
p->data = e; p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return 1;
}

bool DeQueue(LinkQueue& Q) {
if (Q.front == Q.rear) return false;
QueuePtr p;
p = Q.front->next;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front;
free(p);
return true;
}
void print(LinkQueue Q) {
QueuePtr p = Q.front ->next;
while (p) {
cout << p->data <<" ";
p = p->next;
}
}
int main() {
LinkQueue q;
InitQueue(q);
printf("请输入度列的长度: ");
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
EnQueue(q, temp);
}
print(q);
cout << endl;
LinkQueue t = q;
cout << t.front<<endl;
cout << t.rear << endl;
cout << t.front->next->data << t.rear->data <<endl;
DeQueue(q);
print(q);
cout << endl;
EnQueue(q,5);
print(q);
cout << endl;
if(DestroyQueue(q))
cout << "Destroy Queue completely";
return 0;
}
Author: superzhaoyang
Link: http://yoursite.com/2019/09/21/队列的实现/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝

Comment