用动态开辟的存储空间来实现队列的操作 满足先进先出的条件,可以从队列前面插入,后面移出。也可以从队列的前面移出,后面插入。
本代码实现的是从队列的前面插入,后面移出。
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;
}

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

被折叠的 条评论
为什么被折叠?



