链队列的基本操作(带头结点)

  1. Node.h
#ifndef NODE_H
#define NODE_H
#include 
#include  

typedef int QElement;

//结点类型定义
typedef struct Node
{
    int value;
    struct Node *next;
}QueueNode;

typedef struct Queue
{
    QueueNode *front;//设置队头
    QueueNode *rear;//设置队尾 
}Queue;

#endif
  1. Queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include "Node.h"

void InitQueue(Queue *q);
void EnterQueue(Queue *q, QElement x);//进队列
void DeleteQueue(Queue *q, QElement *x);//出队列,用*x存放所出队的元素
void ShowQueue(Queue *q);

#endif
  1. Queue.c

#include "Node.h"

void InitQueue(Queue *q)
{
    q->front = (QueueNode*)malloc(sizeof(Queue));
    if (NULL == q->front)
    {
        printf("malloc free failed!\n ");
        return;
    }
    q->rear = q->front;
    q->front->next= NULL;//使用带有头节点指针的链队列,简单
}

void EnterQueue(Queue *q, QElement x)
{
    QueueNode *pNew = (QueueNode*)malloc(sizeof(QueueNode));
    if (NULL == pNew)
    {
        printf("malloc free failed!\n ");
        return;
    }
    pNew->value = x;
    pNew->next = NULL;
    q->rear->next = pNew;
    q->rear = pNew;
}

void DeleteQueue(Queue *q,QElement *x)
{
    if (q->front == q->rear)
    {
        printf("队列为空!\n");
        return;
    }
    QueueNode*  pNode = q->front->next;
    q->front->next = pNode->next;
    if (q->rear == pNode)
    {
        q->rear = q->front;

    }
    *x = pNode->value;
    free(pNode);
    pNode = NULL;

}
void ShowQueue(Queue *q)
{

    QElement x;
    while (q->rear != q->front)
    {
        DeleteQueue(q, &x);
        printf("%d\t", x);
    }
    free(q->front);
    q->front = NULL;
}

  1. main.c
#include "Node.h"
#include "Queue.h"

int main(void)
{
    Queue q;
    InitQueue(&q);
    EnterQueue(&q, 1);
    EnterQueue(&q, 2);
    EnterQueue(&q, 3);
    EnterQueue(&q, 4);
    ShowQueue(&q);

    return 0;
}

链队列的基本操作(带头结点)_第1张图片

你可能感兴趣的:(链队列的基本操作(带头结点))