不带头节点链队列的基本操作的实现

// 不带头节点的链队列实现--殷人昆教材c语言第2版.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;
typedef int elemtype;
typedef struct Node {
    elemtype data;
    struct Node* next;
}LinkNode;
typedef struct {
    LinkNode* front, *rear;
}LinkQueue;
void init(LinkQueue& q)
{
    q.front = q.rear = NULL;
}
int enqueue(LinkQueue& q,elemtype x)
{
    LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
    s->data = x; s->next = NULL;
    if (q.rear == NULL)
    {      
        q.front = q.rear = s;
    }
    else
    {
        q.rear->next = s; 
        q.rear = s;
    }
    return 1;
}
int dequeue(LinkQueue& q, elemtype& x)
{
    if (q.rear == NULL)return 0;
    LinkNode* p = q.front; x = p->data;
    q.front = p->next;//队头被修改,释放原对头节点
    free(p);
    if (q.front == NULL)q.rear = NULL;
    //队列只有一个元素,被删除,front==null;;所以避免rear悬空做修改处理,空队列条件q.front = q.rear = NULL;
    return 1;
}
int getfront(LinkQueue& q, elemtype& x)
{
    if (q.front == NULL)return 0;
    x = q.front->data;
    return 1;
}
int empty(LinkQueue q)
{
    return q.front == NULL;//写的多好
}
int size(LinkQueue& q)
{
    int j = 0;
    LinkNode* p = q.front;
    while (p)
    {
        j++;//j对应循环条件中p是第几个节点
        cout << p->data << "   ";
        p = p->next;      
    }
    return j;
}
int main()
{
    LinkQueue q;//不用申请一个LinkQueue节点,因为初始化时,q.rear=q.front=NULL,已经进行处理,刘畅教材写的不够简练
    init(q);
    enqueue(q, 1);
    enqueue(q, 2);
    enqueue(q, 3);
    enqueue(q, 4);
    int k=size(q);
    std::cout << "Hello World!\n";
    cout << k<<endl;
    elemtype x;
    dequeue(q,x);
    cout << x << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值