数据结构练习(队列)

题目要求:
定义一个队列,要求用链表实现,使其具有如下功能:
(1)初始化队列,要求得到一个空队列;
(2) 入队操作,将一个元素放入队列中;
(3) 出队操作,将元素从队列中删除;
(4) 销毁队列。
以上每一步都做成函数,并给出相关代码。
参考代码:

#include <stdio.h>
#include <stdlib.h>

/* 队列的头结点不存元素 */

//定义结构体
struct qnode{  
    int   data ;
   struct qnode  *next;
};

//定义队列 
struct link_queue{   
	struct qnode  *front,*rear ; //队头,队尾
};

//初始化队列
struct link_queue* init_queue(){
	struct link_queue* q=(struct link_queue*)malloc(sizeof(struct link_queue));
    q->front = NULL;
    q->rear = NULL;
	
    struct qnode* node=(struct qnode*)malloc(sizeof(struct qnode));
    node->data= NULL;
    node->next = NULL;
    
    q->front = node;
    q->rear = node;
    return q;
}

//插入队列元素 
struct link_queue* insert_queue(struct link_queue* q,int num){
	struct qnode* node=(struct qnode*)malloc(sizeof(struct qnode));
	node->data=num;
	node->next=NULL;
	
	q->rear->next=node;
	q->rear=node;
	
	return q;
} 
//删除队列元素
struct link_queue* delete_queue(struct link_queue* q){
	if(q->front==q->rear){
        return q;
	} 
    
    if(q->front->next->next==NULL){
		q->rear=q->front;
        free(q->front->next);
        q->front->next=NULL;
        return q;
    }
	
    struct qnode *temp=q->front->next;
	q->front->next=q->front->next->next;
    free(temp);
     return q;
} 
//销毁队列
void destroy_queue(struct link_queue* q){
   while(q->front!=q->rear){
	q=delete_queue(q);
   }
    free(q->front);
	free(q);
    printf("队列已销毁!\n");
    return;
    
} 

//显示队列元素 
void print_queue(struct link_queue* q){
	struct qnode *temp=q->front->next;
	if(q->front==q->rear){
		printf("队列元素为空!\n");
        return;
	} 
    
	printf("队列元素有:");
	for(temp;;temp=temp->next){
		if(temp->next!=NULL){
			printf("%d,",temp->data);
        }else{
			printf("%d\n",temp->data);
			break;
		}
    }	
   
}


int main(int argc, char *argv[]) {
	struct link_queue* result;
	
	//初始化 
	result=init_queue();
    //打印
	print_queue(result);
    
	//入队5个元素
	result=insert_queue(result,1);
	result=insert_queue(result,2);
    result=insert_queue(result,3);
    result=insert_queue(result,4);
    result=insert_queue(result,5);
    //打印
    print_queue(result);
	
    //出队1个元素
	result=delete_queue(result);
    //打印
    print_queue(result);
	
    //销毁队列
    //destroy_queue(result);
			
    system("pause");
	return 0;
}

运行结果:
(1)初始化队列,得到一个空队列,此时打印结果:
在这里插入图片描述

(2)入队操作,将一个元素放入队列中;
在这里插入图片描述

(3)出队操作,将元素从队列中删除;
在这里插入图片描述

(4)销毁队列。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值