C/C++语言之链队列

链队列

—— 链表表示的队列(定义)。限定操作的链表

—— 便于操作:设指向表头和表尾的两个指针

—— 便于操作:链表带头结点

源代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define ElemType int
#pragma warning( disable : 4996)
typedef  struct  node    // 链表结点
{
    ElemType data;
    node *next;
} NODE, *pNODE;  
typedef  struct         //链队列
{
    NODE  *front, *rear;
}  LQueue, *pLQueue;
void Creat_Init(pLQueue s)
{
    pNODE head = (pNODE)malloc(sizeof(node));
    if (head == NULL){ printf("内存分配失败\n"); }
    head->next = NULL;
    s->front = s->rear = head;
}
void Queue_In(pLQueue s,ElemType x)//从队尾插入数据
{
    pNODE pnew = (pNODE)malloc(sizeof(node));
    if (pnew == NULL){ printf("内存分配失败\n"); }
    
    pnew->data = x;
    pnew->next = NULL;
    s->rear->next = pnew;
    printf("插入栈队列元素为:%d\n", pnew->data);
    s->rear =s->rear->next;
}
void Queue_Out(pLQueue s)//从队头删除数据
{
    while(s->front != s->rear)
    {
        printf("出栈队列头元素为:%d\n",s->front->next->data);
        s->front= s->front->next;
    }
}
void Queue_IsEnmpty(pLQueue s)//验证队列是否为空
{
    if (s->front=s->rear)
    {
        printf("栈队列为空\n");
    }
}
LQueue ss;
int n, m;
int main()
{
    Creat_Init(&ss);
    printf("请输入插入链队列元素个数:\n");
    scanf("%d", &n);
    for (int i = 1; i <n+1; i++)
    {
        printf("请输入第 %d 个元素:\n", i);
        scanf("%d", &m);
        Queue_In(&ss,m);
    }
    Queue_Out(&ss);
    Queue_IsEnmpty(&ss);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39016425/article/details/84037391