队列(单链表)

 

 


头文件

#pragma once

//利用带头节点的单链表实现队列,队头为第一个数据节点

typedef struct Node
{
   int data;
   struct Node *next;
}Node;//数据节点

typedef struct HNode
{
    struct Node *front;//队头指针
    struct Node *rear;//队尾指针
}HNode,*PLQueue;//头节点

void InitQueue(PLQueue pl);

//入队
bool Push(PLQueue pl,int val);

//获取队头的值,但不删除
bool GetTop(PLQueue pl,int *rtval);

//获取队头的值,且删除
bool Pop(PLQueue pl,int *rtval);

bool IsEmpty(PLQueue pl);

void Destroy(PLQueue pl);

cpp文件

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "lqueue.h"
//利用带头节点的单链表实现队列,队头为第一个数据节点

void InitQueue(PLQueue pl)
{
    assert(pl != NULL);
    pl->front = NULL;
    pl->rear = NULL;
}

//入队
bool Push(PLQueue pl,int val)
{
    Node *p = (Node *)malloc(sizeof(Node));
    p->data = val;
    p->next = NULL;

    if(IsEmpty(pl))
    {
    pl->front = p;
    pl->rear = p;
    }
    else
    {
    pl->rear->next = p;
    pl->rear = p;
    }

    return true;
}

//获取队头的值,但不删除
bool GetTop(PLQueue pl,int *rtval)
{
    if(IsEmpty(pl))
    {
    return false;
    }
    if(rtval != NULL)
    {
    *rtval = pl->front->data;
    }
    return true;
}

//获取队头的值,且删除
bool Pop(PLQueue pl,int *rtval)
{
    if(IsEmpty(pl))
    {
    return false;
    }
    if(rtval != NULL)
    {
    *rtval = pl->front->data;
    }
    Node *p = pl->front;
    pl->front = p->next;
    free(p);
    if(pl->front == NULL) //已经删除最后一个节点
    {
    pl->rear = NULL;
    }

    return true;
}

bool IsEmpty(PLQueue pl)
{
    return pl->front == NULL;
}

void Destroy(PLQueue pl)
{
    Node *q;
    for(Node *p = pl->front;p->next != NULL;p = p-> next)
    {
        q = p;
        free(q);
    }
    pl -> front = NULL;
    pl -> rear = NULL;
}

主函数

#include <stdio.h>
#include "lqueue.h"

int main()
{
    HNode head;
    InitQueue(&head);
    for(int i=0;i<15;i++)
    {
	Push(&head,i);
    }
    int tmp;
    while(!IsEmpty(&head))
    {
	Pop(&head,&tmp);
	printf("%d\n",tmp);
    }
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值