队列的链式表示

队列的链式结构

  • 不带头结点
  1. 队空 Q.front == Q.rear == head
  • 带头结点
  1. 队空 Q.front == Q.rear ==&第一个节点
#include<stdio.h>
#include<malloc.h>

typedef int ElemType;

typedef struct Node{
    ElemType data;
    struct Node *next;
}Node;

typedef struct{
    Node *front;
    Node *rear;
    int length;
}Queue;

void init_queue(Queue *q){
    q->front = q->rear =(Node *)malloc(sizeof(Node));
    q->front->next = NULL;
    q->length = 0;
}

void show(Queue *q){
    if(q->front == q->rear){
        printf("THE QUEUE IS EMPTY\n");
        return ;
    }
    Node *p = q->front;
    while(p < q->rear){
        printf("%2d",p->data);
        p = p->next;
    }
    printf("\n");
}


void push(Queue *q,ElemType e){
    Node * p = (Node *)malloc(sizeof(Node));
    q->rear->data = e;
    q->rear->next = p;
    q->rear = p;
    q->length++;
}

void pop(Queue *q,ElemType *e){
    if(q->front == q->rear){
        printf("THE QUEUE IS EMPTY\n");
        return ;
    }
    Node *p = q->front;
    *e = p->data;
    q->front = p->next;
    q->length--;
    //if(p == q->rear)
        //q->rear = q->front;
    free(p);
}

int main(){
    Queue queue;
    ElemType e;
    init_queue(&queue);

    push(&queue,2);
    push(&queue,4);
    show(&queue);

    pop(&queue,&e);
    show(&queue);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值