链式队列

用链表来实现的队列为链式队列。用指针front和rear分别指向队头和队尾。同顺序队列一样,也是在front处出队,在rear处入队。
与顺序队列不同,链式队列的rear指针指向最后一个元素。

链式队列的C语言实现:(codeblocks完美运行)

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    int data;
    struct node *next;
}pNode;

typedef struct Queue
{
    pNode *front;
    pNode *rear;
    int size;
}queue;

queue *create()
{
    queue *lq = (queue*)malloc(sizeof(queue));
    lq->front = NULL;
    lq->rear = NULL;
    lq->size = 0;
}

int getsize(queue *lq)
{
    return lq->size;
}

int IsEmpty(queue *lq)
{
    if(lq->size == 0)
        return 1;
    return 0;
}

void insert(queue *lq,int val)
{
    pNode *pn = (pNode*)malloc(sizeof(pNode));
    pn->data = val;
    pn->next = NULL;
    if(IsEmpty(lq))
    {
        lq->front = pn;
        lq->rear = pn;
    }
    else
    {
        lq->rear->next = pn;
        lq->rear = pn;
    }
    lq->size++;
}

int getfront(queue *lq)
{
    if(IsEmpty(lq))
    {
        printf("队列已为空");
        return 0;
    }
    return lq->front->data;
}


int getrear(queue *lq)
{
    if(IsEmpty(lq))
    {
        printf("队列已为空");
        return 0;
    }
    return lq->rear->data;
}

pNode *del(queue *lq)
{
    if(IsEmpty(lq))
    {
        printf("队列为空,删除错误!\n");
        return NULL;
    }
    pNode *temp = lq->front;
    lq->front = temp->next;
    lq->size--;
    return temp;
}

void clear(queue *lq)
{
    lq->front = NULL;
    lq->rear = NULL;
    lq->size = 0;
    printf("\n队列已清空!\n");
}

int main()
{
    queue *lq = create();
    srand((unsigned)time(0));
    printf("入队30个元素\n");
    int i;
    for(i=0;i<30;i++)
        insert(lq,rand()%300);
    printf("队头元素为:%d\n",getfront(lq));
    printf("队尾元素为:%d\n",getrear(lq));
    printf("队列大小为:%d\n",getsize(lq));
    printf("打印队列,同时也是出队操作!\n");
    for(i=0;i<30;i++)
    {
        if(i%6 == 0)
            printf("\n");
        printf("%3d  ",*((int *)del(lq)));
    }
    clear(lq);
    return 0;
}


运行界面:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值