一、链式队列进队、出队、遍历、判空
1、02_linkqueue.c
#include <stdio.h>
#include <stdlib.h>
#include "./02_linkqueue.h"
linkPos* create_linkqueue(void)
{
linkPos* pos = (linkPos*)malloc(sizeof(linkPos));
//pos指向的堆空间中包含linkqueue空间的front和rear两部分,
pos->front = (linkqueue*)malloc(sizeof(linkqueue));
if(pos->front == NULL)
{
printf("创建链式队列失败\n");
return NULL;
}
(pos->front)->text.len = 0;
(pos->front)->next = NULL;
pos->rear = pos->front;
return pos;
}
//尾进头删
void push_linkQueue(linkPos* pos,dataType num)
{
linkqueue* temp = (linkqueue*)malloc(sizeof(linkqueue));
if(NULL == temp)
{
printf("创建新节点失败\n");
return;
}
temp->text.data = num;
temp->next = NULL;
temp->next = (pos->rear)->next;
(pos->rear)->next = temp;
pos->rear = (pos->rear)->next;
(pos->front)->text.len++;
}
//判空
int Empty(linkPos* pos)
{
if(pos->front == pos->rear)
{
return 1;
}
else
{
return 0;
}
}
//(头出)出队
dataType pop_linkQueue(linkPos* pos)
{
if(Empty(pos) == 1)
{
printf("此队列已空,无法进行删除操作\n");
return (dataType)-1;
}
linkqueue* temp;
dataType n;
temp = pos->front->next;
pos->front->next = pos->front->next->next;
n = temp->text.data;
free(temp);
temp = NULL;
pos->front->text.len--;
return n;
}
//遍历队列
void show_linkQueue(linkPos* pos)
{
while(pos->front->next != NULL)
{
pos->front = pos->front->next;
printf("%d ",pos->front->text.data);
}
printf("\n");
}
2、02_linkqueue.h
#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
typedef int dataType; //由于实际应用中数据不一定是整型,所以重名方便操作
union msg{
dataType data; //有效数据结点中的数据使用
int len; //头结点中的数据使用
};
typedef struct node{ //由于结点中的指针域要指向下一个结点,所以必须用有名结构体
union msg text; //数据域.若是头结点,则使用text里面的len.若是有效数据结点,就使用text里面的data
struct node* next; //指针域,存储下一个结点的地址
}linkqueue;
//因为front和rear都需要返回,而return只能返回一个值,
//所以将front和rear打包在一起,方便封装函数返回
typedef struct
{
linkqueue* front;
linkqueue* rear;
}linkPos;
linkPos* create_linkqueue(void);
//尾进头删
void push_linkQueue(linkPos* pos,dataType num);
//判空
int Empty(linkPos* pos);
//(尾出)出队
dataType pop_linkQueue(linkPos* pos);
//遍历队列
void show_linkQueue(linkPos* pos);
#endif
3、02_main.c
#include <stdio.h>
#include "./02_linkqueue.h"
int main(int argc, const char *argv[])
{
linkPos* pos = create_linkqueue();
push_linkQueue(pos,111);
push_linkQueue(pos,222);
push_linkQueue(pos,333);
int num = pop_linkQueue(pos);
printf("%d\n",num);
show_linkQueue(pos);
return 0;
}