数据结构队列c++

数据结构中队列的基本操作(链式存储结构)
初始化,入队,出队,销毁。
下面展示代码

# include<iostream>
# include <stdlib.h>
using namespace std;
struct z{
    char data;
    struct z *next;
};//定义链表结构体
struct queue{
    struct z *head;
    struct z *tail;
};//定义指向链表头和尾的指针
struct queue* init_queue(){
    struct queue *q;
    struct z *queue_head;
    q=(struct queue*)malloc(sizeof(struct queue));
    queue_head=(struct z*)malloc(sizeof(struct z));
    if(q!=NULL&&queue_head!=NULL){
        queue_head->next=NULL;
        queue_head->data=-1;
        q->head=queue_head;
        q->tail=queue_head;
        return q;
    }
    else
    exit(0);
}//初始化
int push_queue(char a,struct queue *q){
    struct z* s=(struct z*)malloc(sizeof(struct z));
    if(s!=NULL){
        s->data=a;
        s->next=NULL;
        q->tail->next=s;
        q->tail=s;
        return 1;
    }
    return 0;
}//入队
void get_queue(struct queue *q,char *s){
    if(q->head!=q->tail&&q->head->next!=NULL){
        *s=q->head->next->data;
    }
}//取得队列当前位置元素
void pop_queue(struct queue *q){
    if(q->head!=q->tail&&q->head->next!=NULL){
        q->head=q->head->next;
    }
}//使得队列位置向后移一位,与get_queue结合使用
//出队
void break_queue(struct queue *q)
{
    while(q->head!=q->tail){
        q->head=q->head->next;
    }
}//销毁
int main(){
    struct queue *queue=init_queue();
    char a;
    for(a='1';a<='9';++a){
        push_queue(a,queue);
    }
    char b;
    while(queue->head!=queue->tail){
        get_queue(queue,&b);
        cout<<b<<endl;
        pop_queue(queue);
    }
    break_queue(queue);
    if(queue->head==queue->tail)
        cout<<"empty"<<endl;
    free(queue);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值