#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
typedef int data_t;
typedef struct linknode
{
data_t* data;
struct linknode* next;
}linkqueue, *plinkqueue;
//创建头结点
plinkqueue queue_creat();
//新节点队尾入队
int enqueue(plinkqueue p, data_t val);
//队首出队
data_t dequeue(plinkqueue p);
//打印队列
void queue_show(plinkqueue p);
//释放动态开辟的空间
plinkqueue queue_free(plinkqueue p);
头文件LinkQueue.h
#include "LinkQueue.h"
plinkqueue queue_creat()
{
plinkqueue p;
p = (plinkqueue)malloc(sizeof(linkqueue));
if(p == NULL)
{
return NULL;
}
memset(p, 0, sizeof(linkqueue));
p->data = (data_t*)malloc(sizeof(data_t));
if(p->data == NULL)
{
free(p);
return NULL;
}
*(p->data) = 0;
p->next = NULL;
return p;
}
int enqueue(plinkqueue p, data_t val)
{
if(p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
while(p->next != NULL)
{
p = p->next;
}
plinkqueue newnode;
newnode = queue_creat();
*(newnode->data) = val;
p->next = newnode;
return 0;
}
data_t dequeue(plinkqueue p)
{
if(p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
data_t temp = 0;
temp = *(p->next->data);
p->next = p->next->next;
return temp;
}
void queue_show(plinkqueue p)
{
printf("address\tvalue\tnext\n");
while(p->next != NULL)
{
printf("%p\t%d\t%p\n", p->next, *(p->next->data), p->next->next);
p = p->next;
}
}
plinkqueue queue_free(plinkqueue p)
{
if(p == NULL)
{
printf("Pointer is NULL.\n");
return NULL;
}
free(p->data);
free(p);
return NULL;
}
函数实现LinkQueue.c
#include "LinkQueue.h"
int main()
{
plinkqueue p;
p = queue_creat();
enqueue(p, 21);
enqueue(p, 22);
queue_show(p);
printf("############\n");
enqueue(p, 24);
queue_show(p);
printf("############\n");
data_t ret = 0;
ret = dequeue(p);
queue_show(p);
printf("############\n");
printf("value:> %d\n", ret);
p = queue_free(p);
return 0;
}
测试函数test.c
运行结果:
头结点总是指向队首元素,执行三次入队操作后,队首元素值为21,队尾元素值为24。执行一次出队操作后,原先的队首元素21出队,头结点指向新的队首22,得到出队元素的值value为21。