队列(二)队列的链表存储

#include<stdio.h>
#define false 0
#define ok 1

//定义队列每个节点的结构
typedef struct node
{
    int data;
    struct node *next;
}node,*qnode;//相当于typedef struct node * qnode;

//定义整个队列结构
typedef struct squeue
{
    qnode front, rear;
}squeue;

//建立一个空的队列
void initqueue(squeue *l)
{
    l->front=(qnode)malloc(sizeof(node));
    l->rear=(qnode)malloc(sizeof(node));
    l->front->next = NULL;
    l->rear->next = NULL;
}

//入队列
void inqueue(squeue *l, int e)
{

    qnode s=(qnode)malloc(sizeof(node));
    s->data = e;
    s->next = NULL;
    if (l->front->next == NULL)
    {
        l->front->next = s;
        l->rear = s;
    }
    else
    {
        l->rear->next = s;
        l->rear = s;
    }
}

//出队列
int outqueue(squeue *l, int *e)
{
    if (l->front == l->rear)
        return false;
    qnode s= l->front->next;
    *e = s->data;
    l->front->next = s->next;
    if (l->rear == s)    //如果删除的是尾节点,此时队列为空
        l->rear = l->front;
    free(s);
    return ok;
}

//查看队列
void seequeue(squeue l)
{
    if (l.rear == l.front)
        printf("队列为空");
    qnode s= l.front->next;
    while (s)
    {
        printf("%4d", s->data);
        s = s->next;
    }
    free(s);
}

int main(void)
{
    int a;
    squeue q;
    initqueue(&q);
    inqueue(&q, 2);
    inqueue(&q, 3);
    seequeue(q);
    outqueue(&q, &a);
    seequeue(q);
    outqueue(&q, &a);
    seequeue(q);
    return 0;
}

定义了一个队列结构,front作为头指针,front->next指向队列头,rear指向队列尾。
一开始调试一直出错是在入队列时忘了对队列是否为空进行判断,第一个元素插入的方法和以后的元素不一样,第一个元素需要让front->next指向它,rear直接指向它。
刚申明的指针要指向null,后面再让它保存的地址更改,在windows中指针p指向null相当于p的值为0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值