#include <bits/stdc++.h>
// Date type
typedef int Elemtype;
/* Node type */
typedef struct Node {
Elemtype date;
struct Node* next;
} Node_t, *Node_p;
/* Chained queue type */
typedef struct
{
Node_p front;
Node_p rear;
} Chained_Queue_t, *Chained_Queue_p;
/* Creat One Queue */
Chained_Queue_p CreatQueue(void)
{
Chained_Queue_p newQueue = (Chained_Queue_p)malloc(sizeof(Chained_Queue_t));
if (!newQueue)
return NULL;
newQueue->front = newQueue->rear = (Node_p)malloc(sizeof(Node_t));
if (newQueue->front == NULL) {
free(newQueue);
return NULL;
}
newQueue->front->next = NULL;
return newQueue;
}
typedef int8_t Q_Status;
#define QNULL 1
#define QEMPTY 2
Q_Status isQueueNULL(Chained_Queue_p q)
{
return q == NULL ? QNULL : 0;
}
Q_Status isQueueEmpty(Chained_Queue_p q)
{
return q->front == q->rear ? QEMPTY : 0;
}
Q_Status ClearQueue(Chained_Queue_p q)
{
if (isQueueNULL(q))
return QNULL;
if (isQueueEmpty(q))
return QEMPTY;
Node_p temp;
while (q->front != q->rear) {
temp = q->front->next;
free(q->front);
q->front = temp;
}
return QEMPTY;
}
Q_Status DelQueue(Chained_Queue_p q)
{
if (isQueueNULL(q))
return QNULL;
Node_p temp;
while (q->front != q->rear) {
temp = q->front->next;
free(q->front);
q->front = temp;
}
free(q->front);
free(q);
return QNULL;
}
#define ERRORMALLOC 3
Q_Status EnQueue(Chained_Queue_p q, Elemtype e, void CopyFuc(Elemtype*, const Elemtype*))
{
if (isQueueNULL(q))
return QNULL;
Node_p temp = q->front;
while (temp != q->rear) {
temp = temp->next;
}
Node_p newnode = (Node_p)malloc(sizeof(Node_t));
if (!newnode)
return ERRORMALLOC;
newnode->next = NULL;
CopyFuc(&(temp->date), &e);
temp->next = newnode;
q->rear = newnode;
return 0;
}
Q_Status DeQueue(Chained_Queue_p q, Elemtype* e, void CopyFuc(Elemtype*, const Elemtype*))
{
if (isQueueNULL(q))
return QNULL;
if (isQueueEmpty(q))
return QEMPTY;
CopyFuc(e, &(q->front->date));
Node_p temp = q->front->next;
free(q->front);
q->front = temp;
return 0;
}
void visit(Elemtype* date)
{
printf("%d", *date);
}
Q_Status Queue_Info(Chained_Queue_p q)
{
if (isQueueNULL(q)) {
printf("NULL Queue.\n");
return QNULL;
}
if (isQueueEmpty(q)) {
printf("Empty Queue.\n");
return QEMPTY;
}
Node_p temp = q->front;
while (temp != q->rear) {
visit(&temp->date);
temp = temp->next;
}
return 0;
}
void ElemCopy(Elemtype* dst, const Elemtype* src)
{
*dst = *src;
}
int main(void)
{
Chained_Queue_p q = CreatQueue();
int a[10];
for (int i = 0; i < 10; i++) {
EnQueue(q, i+1, ElemCopy);
}
for (int i = 0; i < 10; i++) {
DeQueue(q, a + i, ElemCopy);
}
printf("\n");
DelQueue(q);
}
链队列的实现
最新推荐文章于 2024-08-19 23:56:23 发布