队列——队列的链式存储结构设计思路与实现

 

 

总的实现代码:

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

typedef struct{
	char name[100];
	char id[100];
}ElemType;

// 定义节点结构
typedef struct Node {
    ElemType data;               // 节点数据
    struct Node* next;      // 指向下一个节点的指针
} Node;

// 定义队列结构
typedef struct Queue {
    Node* front;           // 队头指针
    Node* rear;            // 队尾指针
    int Size;
} Queue;

// 初始化队列
void InitQueue(Queue* q) 
{
    q->front = NULL;
    q->rear = NULL;
    q->Size = 0;
}

// 判断队列是否为空
bool Empty(Queue* q)
{
	if(q->front == NULL) 
        return true;
    return false;
}

// 入队操作
void Push(Queue* q, ElemType value)
{
    Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
    newNode->data = value;
    newNode->next = NULL; // 新节点的下一个指针为空

    if (Empty(q))
	{
        q->front = newNode; // 如果队列为空,队头和队尾都指向新节点
        q->rear = newNode;
    } 
	else 
	{
        q->rear->next = newNode; // 将新节点链接到队尾
        q->rear = newNode;       // 更新队尾指针
    }
    q->Size++;
}

// 出队操作
bool Pop(Queue *q, ElemType *e) 
{
    if (Empty(q))
    {
    	e = NULL;
    	return false; // 返回一个错误值
	}
        
    Node* temp = q->front; // 临时保存队头节点
    if(e != NULL)  // 判断作为返回值的参数是否为空 
        *e = temp->data;
    q->front = q->front->next; // 更新队头指针

    if (q->front == NULL)    // 如果队列为空,更新队尾指针
	{
        q->rear = NULL;
    }
    free(temp); // 释放被出队节点的内存
    temp = NULL;
    --q->Size;
    return true; // 返回出队的数据
}

// 查看队头元素
ElemType* Front(Queue* q)
{
    if (Empty(q))
        return NULL;
    return &(q->front->data); // 返回队头元素
}

int Size(Queue *q)
{
    return q->Size;
}

void Clear(Queue *q)
{
	while(Size(q) != 0)
	{	
		Pop(q, NULL);
	}
} 

// 主函数示例
int main() 
{
	ElemType arr[20] = {
	    {"张三", "0x001"},
	    {"李四", "0x002"}
	};
	Queue queue;
	InitQueue(&queue);
    Push(&queue, arr[0]);
    Push(&queue, arr[1]);
    
    ElemType *e = Front(&queue);
    printf("队首元素为:%s  %s\n", e->name, e->id);
    printf("队列中元素个数为:%d\n", Size(&queue)); 
    
    Pop(&queue, e);
    printf("队列中元素个数为:%d\n", Size(&queue));
    e = Front(&queue);
    if(e != NULL)
        printf("队首元素为:%s  %s\n", e->name, e->id);
    
    if(Empty(&queue))
		printf("队列空\n");
    else
    	printf("队列非空\n");
	
    Clear(&queue);  // 清空队列 
    printf("队列中元素个数为:%d\n", Size(&queue));
    return 0;
}

 

请登录后发表评论

    没有回复内容