在C语言中,链式队列是一种使用链表实现的队列,它具有以下特点:
- 链式队列不需要预先分配固定大小的存储空间,可以动态地分配内存以适应不同大小的队列。
- 链式队列可以无限扩展,因此不会出现队列满的情况。
- 链式队列的入队和出队操作对于链表而言比较灵活,不需要移动大量元素
以下是对链式队列的实现和简单使用
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//节点结构体
struct Linknode
{struct Linknode* next;
};
struct LQueue
{struct Linknode pHeader;int m_size;struct Linknode* pTail;//尾节点指针
};
typedef void* linkqueue;
//初始化
linkqueue init_linkqueue()
{struct LQueue* myqueue = (struct LQueue*)malloc(sizeof(struct LQueue));if (myqueue == NULL){return NULL;}myqueue->pHeader.next = NULL;myqueue->m_size = 0;myqueue->pTail = &myqueue->pHeader;return myqueue;
}
//入队,尾插
void push_linkqueuq(linkqueue queue,void*data)
{if (queue == NULL){return ;}if (data == NULL){return;}struct LQueue* myqueue = (struct LQueue* )queue;struct Linknode* mynode = (struct Linknode* )data;//更改过指针指向myqueue->pTail->next = mynode;mynode->next = NULL;myqueue->pTail = mynode;myqueue->m_size++;
}
//出队,头删
void pop_linkqueue(linkqueue queue)
{if (queue == NULL){return;}struct LQueue* myqueue = (struct LQueue*)queue;if (myqueue->m_size == 0){return;}if (myqueue->m_size == 1){myqueue->pHeader.next = NULL;myqueue->pTail = &myqueue->pHeader;myqueue->m_size--;return;}struct Linknode* pFirst = myqueue->pHeader.next;myqueue->pHeader.next = pFirst->next;myqueue->m_size--;
}
//返回队头
void* front_linkqueue(linkqueue queue)
{if (queue == NULL){return NULL;}struct LQueue* myqueue = (struct LQueue*)queue;if (myqueue->m_size == 0){return NULL;}return myqueue->pHeader.next;
}
//队尾
void* back_linkqueue(linkqueue queue)
{if (queue == NULL){return NULL;}struct LQueue* myqueue = (struct LQueue*)queue;if (myqueue->m_size == 0){return NULL;}return myqueue->pTail;
}
//大小
int size_linkqueue(linkqueue queue)
{if (queue == NULL){return -1;}struct LQueue* myqueue = (struct LQueue*)queue;return myqueue->m_size;
}
//判断是否为空
int isEmpty(linkqueue queue)
{if (queue == NULL){return -1;}struct LQueue* myqueue = (struct LQueue*)queue;if (myqueue->m_size == 0){return 1;}return 0;
}
//销毁
void destroy_linkqueue(linkqueue queue)
{if (queue == NULL){return;}free(queue); // 释放内存queue = NULL; // 将指针置为 NULL
}
struct person
{int* a;char name[64];int age;
};void test01()
{linkqueue myqueue = init_linkqueue();struct person p6 = { NULL, "aaa",18 };struct person p7 = { NULL, "bbb",123 };struct person p8 = { NULL ,"ccc",24 };struct person p9 = { NULL,"ddd",25 };push_linkqueuq(myqueue, &p6);push_linkqueuq(myqueue, &p7);push_linkqueuq(myqueue, &p8);push_linkqueuq(myqueue, &p9);printf("大小:%d\n", size_linkqueue(myqueue));while (!isEmpty(myqueue)){struct person* p1 = (struct person* )front_linkqueue(myqueue);printf("队头名字:%s,年龄:%d\n", p1->name, p1->age);struct person* p2 = (struct person*)back_linkqueue(myqueue);printf("队尾名字:%s,年龄:%d\n", p2->name, p2->age);printf("-------\n");pop_linkqueue(myqueue);}printf("大小:%d\n", size_linkqueue(myqueue));destroy_linkqueue(myqueue);
}
int main()
{test01();return 0;
}