#include <stdio.h> #include <stdlib.h>

typedef int Status; typedef int ElemType; typedef struct LNode { ElemType data; struct LNode * next; }LNode,LinkList; typedef struct { LinkList front,rear; / 队头、队尾指针 */ }LinkQueue;

Status QueueInsert(LinkQueue *Q, ElemType e) { LNode newNode = (LNode)malloc(sizeof(LNode)); if (newNode == NULL) { return -1; // 内存分配失败 } newNode->data = e; newNode->next = NULL;

if (Q->front == NULL) // 队列为空,新节点既是队头又是队尾
{
    Q->front = newNode;
    Q->rear = newNode;
}
else
{
    Q->rear->next = newNode; // 将新节点插入队尾
    Q->rear = newNode; // 更新队尾指针
}

return 0; // 入队列成功

}

Status QueueDelete(LinkQueue *Q, ElemType *e) { if (Q->front == NULL) // 队列为空,无法出队列 { return -1; }

LNode *temp = Q->front; // 保存队头节点
*e = temp->data; // 保存队头元素值
Q->front = Q->front->next; // 更新队头指针

if (Q->front == NULL) // 如果队头指针为空,说明队列已空,需要更新队尾指针
{
    Q->rear = NULL;
}

free(temp); // 释放队头节点的内存

return 0; // 出队列成功

}

int main() { LinkQueue Q; Q.front = NULL; Q.rear = NULL;

QueueInsert(&Q, 1);
QueueInsert(&Q, 2);
QueueInsert(&Q, 3);

ElemType e;
QueueDelete(&Q, &e);
printf('Deleted element: %d\n', e);

QueueDelete(&Q, &e);
printf('Deleted element: %d\n', e);

QueueDelete(&Q, &e);
printf('Deleted element: %d\n', e);

return 0;

}


原文地址: https://www.cveoy.top/t/topic/pl7R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录