#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
//构造链表节点类型
typedef struct node{
data_t data;
struct node *next;//指针域
}linklist;
//构造链式队列类型
typedef struct{
linklist *front;//保存队头节点的前一个节点的地址
linklist *rear;//保存队尾节点的地址
}lqueue;
//创建空链式队列
lqueue *createLqueue()
{
lqueue *lq = (lqueue *)malloc(sizeof(lqueue));//给链式队列开空间
if(NULL == lq)
return NULL;
lq->front = (linklist *)malloc(sizeof(linklist));//给链表头节点开空间
if(lq->front == NULL)
return NULL;
lq->rear = lq->front;
lq->front->data = -1;
lq->front->next = NULL;
return lq;
}
//判空
int lqueue_is_empty(lqueue *lq)
{
if(NULL == lq)
return -1;
else
return ((lq->front == lq->rear)?1:0);
}
//求队列中节点的个数
int getLengthLqueue(lqueue *lq)
{
if(lq == NULL)
return -1;
int num = 0;
linklist *p = lq->front->next;
while(p != NULL)
{
num++;
p = p->next;
}
return num;
}
//入队,在队尾入队
int enLqueue(lqueue *lq,data_t data)
{
if(NULL == lq)
return -1;
linklist *new = (linklist *)malloc(sizeof(linklist));//准备新节点
if(NULL == new)
return -1;
new->data = data;
new->next = NULL;
//将new节点插入到队尾
lq->rear->next = new;
lq->rear = new;//new节点为队尾节点
return 0;
}
//出队
data_t deLqueue(lqueue *lq)
{
if(lq == NULL)
return -1;
if(lqueue_is_empty(lq))
return -1;
linklist *p = lq->front->next;//p指针保存队头节点的地址
data_t data = p->data;//data变量保存队头元素的data值
//删除队头节点
lq->front->next = p->next;
if(lq->front->next == NULL)//判断队列是否为空
lq->rear = lq->front;//front和rear指针指向头节点
free(p);
p = NULL;
return data;
}
//打印队列中各个节点的daya值
void printLqueue(lqueue *lq)
{
if(NULL == lq)
return;
if(lqueue_is_empty(lq))
return;
linklist *p = lq->front->next;//p变量保存的是队头节点的地址
while(p != NULL)//遍历队列
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
return;
}
int main()
{
lqueue *lq = createLqueue();
if(NULL == lq)
{
printf("malloc failed\n");
return -1;
}
int i = 0;
while(i < 10)
{
enLqueue(lq,i+1);
i++;
}
printLqueue(lq);
i = 0;
while(i<5)
{
data_t data = deLqueue(lq);
printf("%d ",data);
i++;
}
printf("\n");
printLqueue(lq);
return 0;
}
数据结构--8链队程序
于 2023-08-09 23:47:41 首次发布