数据结构中队列的基本操作(链式存储结构)
初始化,入队,出队,销毁。
下面展示代码
。
# 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;
}