#include<stdio.h>
#include <stdlib.h>
//队列,链表实现
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct QNode
{
struct Node *rear;
struct Node *front;
}QNode,*Queue;
Queue q;
void del(Queue q)
{
Node *frontCell;
int frontData;
if(q->front == NULL)
{
printf("队列空\n");
}
frontCell = q->front;
if(q->front == q->rear)
q->front = q->rear = NULL; //只有一个节点时,出队一个,链表为空
frontData = frontCell->data;
printf("%d已出队\n",frontData) ;
q->front = frontCell->next;
free(frontCell);
}
void add(Queue q,int a)
{
Node *frontCell = (Node *)malloc(sizeof(Node));
if(frontCell == NULL)//内存分配失败
return ;
frontCell->data = a;
frontCell->next = NULL;//尾插法,插入元素指向空
if(q->rear == NULL)
{
q->front = frontCell;
q->rear = frontCell;
printf("%d已入队\n",a);
}
else{
q->rear->next = frontCell;//让n成为当前的尾部节点下一节点
q->rear= frontCell;//尾部指针指向n
printf("%d已入队\n",a);
}
}
Queue init(Queue q)
{
q = (Queue)malloc(sizeof(QNode));
q->rear = q->front = NULL;
printf("初始化成功...\n");
return q;
}
void traversal(Queue q)
{
Node *node = (Node *)malloc(sizeof(Node));
node = q->front;
if(node==NULL)
{
return ;
}
while(node!=NULL)
{
printf("%d ",node->data);
node = node->next;
}
printf("\n");
free(node);
}
int main()
{
Queue q = init(q);
add(q,1);
add(q,2);
add(q,3);
add(q,4);
add(q,5);
traversal(q);
del(q);
traversal(q);
return 0;
}
有问题,欢迎评论区一起讨论
本人Hexo博客地址:https://qietingfengyindiary.github.io/