using namespace std;
#include <iostream>
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
typedef char QElemType;
typedef struct QNode {
/************************************************************************/
/*单链队列存储结构 */
/*Went 2011-11-2 10:08 */
/************************************************************************/
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int InitQueue(LinkQueue &Q) {
//initiate an empty queue
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front)
return OVERFLOW;
Q.front -> next = NULL;
return OK;
}
int DestroyQueue(LinkQueue &Q) {
//destroy an existed queue
if (Q.front == NULL)
return ERROR;
while(Q.front) {
Q.rear = Q.front -> next;
free(Q.front);
Q.front = Q.rear;
}
return OK;
}
int ClearQueue(LinkQueue &Q) {
//clear an exitstd queue
if (Q.front == NULL)
return ERROR;
QueuePtr p, q;
Q.rear = Q.front;
p = Q.front -> next;
Q.front -> next = NULL;
while(p) {
q = p;
p = p -> next;
free(q);
}
return OK;
}
int QueueEmpty(LinkQueue Q) {
//whether the queue is empty
if (Q.front == NULL)
return ERROR;
else if (Q.front -> next == NULL)
return TRUE;
else
return FALSE;
}
int QueueLenth(LinkQueue Q) {
//get the length of the queue
if (Q.front == NULL)
return ERROR;
int len = 0;
QueuePtr p;
p = Q.front;
while(p != Q.rear) {
len ++;
p = p -> next;
}
return len;
}
int GetHead(LinkQueue Q, QElemType &e) {
//get the head element of the queue
if (Q.front == Q.rear)
return ERROR;
e = Q.front -> next -> data;
return OK;
}
int EnQueue(LinkQueue &Q, QElemType e) {
//input an element e as the new rear of the queue
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if (!p)
return OVERFLOW;
p -> data = e;
p -> next = NULL;
Q.rear -> next = p;
Q.rear = p;
return OK;
}
int DeQueue(LinkQueue &Q, QElemType &e) {
//delete an element which was the head of the queue
if (Q.front == Q.rear)
return ERROR;
QueuePtr p;
p = Q.front -> next;
e = p -> data;
Q.front -> next = p -> next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return OK;
}
int visit(QElemType e) {
cout << e << " ";
return OK;
}
int QueueTraverse(LinkQueue Q, int (*visit)(QElemType)) {
//visit the queue
if (Q.front == NULL)
return ERROR;
QueuePtr p = Q.front -> next;
while(p != NULL) {
if (!visit(p -> data))
return ERROR;
p = p -> next;
}
cout << endl;
return OK;
}
int main() {
LinkQueue q1;
QElemType e;
InitQueue(q1);
cout << QueueEmpty(q1) << endl;
cout << QueueLenth(q1) << endl;
EnQueue(q1, 'a');
EnQueue(q1, 'b');
GetHead(q1, e);
cout << e << endl;
cout << QueueEmpty(q1) << endl;
cout << QueueLenth(q1) << endl;
QueueTraverse(q1, visit);
DeQueue(q1, e);
cout << e << endl;
QueueTraverse(q1, visit);
system("pause");
return 0;
}
LinkQueue
最新推荐文章于 2022-06-27 21:05:20 发布