用单链表实现队列

#include<iostream>
using namespace std;

struct Node;
typedef Node* PtrToNode;
typedef PtrToNode LiQueue;
typedef PtrToNode Position;

//队列节点
typedef struct qnode 
{
    int data;//数据域
    struct qnode* next;//指针域
} QNode;

typedef struct Node
{
    QNode* front;//队列头部
    QNode* rear;//队列尾部
}Node;

//创建队列
LiQueue CreateLiQueue()
{
	LiQueue q = (PtrToNode)malloc(sizeof(struct Node));
    if (q == NULL)
    {
        cout << "内存分配失败!" << endl;
        //q = NULL;
        return q;
    }
    else
    {
        q->front = NULL;//将队列的头尾赋值为NULL
        q->rear = NULL;
        return q;
    }
}

//判断队列是否为空
bool isEmpty(LiQueue& q) 
{
	if (q && q->front == NULL && q->rear == NULL)
		return true;
	return false;
}

//读入队列当中
void EnQueue(LiQueue& q, int e)
{
    QNode* s = NULL;
    s = (QNode*)malloc(sizeof(QNode)); 
    if (s == NULL)
    {
        cout << "分配内存失败" << endl;
    }
    else
    {
        s->data = e; //将数据传给s
        s->next = NULL;//将s的next指针赋值为NULL
        if (q->rear == NULL)//如果是空队列则将数据赋值给头尾
            q->front = q->rear = s;
        else
        {
            q->rear->next = s;
            q->rear = s;
        }
    }
}

//将数据弹出列表
int DeQueue(LiQueue& q)
{
    int e;
    QNode* t;
    if (q == NULL) return -1;
    t = q->front;
    if (q->front == q->rear)//如果是队列中最后一个数据时
        q->front = q->rear = NULL;
    else
        q->front = q->front->next;
    e = t->data;
    free(t);
    return 0;
}

void  show(LiQueue& q)
{
    qnode* p;//遍历队列的工作指针
    p = q->front->next;
    while (p != NULL)
    {
        cout << p->data << " ";
        p = p->next;
    }
}



int main()
{
    LiQueue q;
    q = CreateLiQueue();//创造队列
    for (int i = 0; i < 10; i++)
    {
        EnQueue(q, i);//将数据输入到队列当中
    }
    show(q);
    cout << endl << "弹出后数据:";
    DeQueue(q);//弹出队列的数据
    show(q);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值