多文件编程动态开辟空间来实现队列的操作 c语言版

本文介绍了如何通过动态开辟的存储空间实现满足先进先出条件的队列操作,并提供了从队列前面插入和后面移出的功能实现。包括初始化、弹出、获取队首元素、检查队列是否为空、是否已满和队列大小等关键方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用动态开辟的存储空间来实现队列的操作 满足先进先出的条件,可以从队列前面插入,后面移出。也可以从队列的前面移出,后面插入。

本代码实现的是从队列的前面插入,后面移出。

queue.h

#ifndef __QUEUE_H__
#define __QUEUE_H__
void push(int number);
int pop();
int front();
int empty();
int full();
int size();
void init();
void deinit();
#endif



queue.c

#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    int num;
    struct node *p_next;
}node;
static node head,tail;
void push(int number){
    node *p_node = (node *)malloc(sizeof(node));
    if(!p_node){
      return;
    }
    p_node->num = number;
    p_node->p_next = head.p_next;
    head.p_next = p_node;
}
int pop(){
    node *p_node = &head;
    int number;
    for (p_node = &head;p_node != &tail;p_node = p_node->p_next){
        node *p_lnext = p_node->p_next;
        if (p_lnext != &tail && p_lnext->p_next == &tail){
	    p_node->p_next =&tail;
	    number = p_lnext->num;
	    free(p_lnext);
	    p_lnext = NULL;
	    break;
        }      
   }
   return number;
}
int front(){
}
int empty(){
    return head.p_next == &tail;
}
int full(){
    return 0;
}
int size(){
    node *p_node = &head;
    int cnt = 0;
    for (p_node = &head;p_node != &tail;p_node = p_node->p_next){
        node *p_lnext = p_node->p_next;
	if(p_lnext != &tail){
	  cnt++;
        }
    }
    return cnt;

}
void init(){
     head.p_next = &tail;
}
void deinit(){
    node *p_tmp;
    while (head.p_next != &tail){
          p_tmp = head.p_next;
	  head.p_next = head.p_next->p_next;
	  free(p_tmp);
	  p_tmp = NULL;
    }
}

mm.c

#include<stdio.h>
int main()
{
    init();
	push(1);
	push(3);
	push(4);
	printf("size = %d\n",size());
	printf("%d\n",pop());
	printf("%d\n",pop());
	printf("%d\n",pop());
	if(empty())printf("the queue is empty.\n");
	deinit();
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值