2008秋-计算机软件基础-实验三 参考源程序

实验三 参考源程序

//软件基础 教材 79 页 习题6 答案
//Eman Lee

#include
<stdio.h>
#include
<stdlib.h>
#define m 5 //队列容量
//定义队列的结构
struct queue 
{
    
int seq[m];//队列元素
    int quelen;//队列中元素个数
    int rear;//队列尾指针
};
//初始化队列
struct queue *initial()
{
    
struct queue * head;
    head
=(struct queue*)malloc(sizeof(struct queue));
    head
->rear=0;
    head
->quelen=0;
    
return head;
}
//入队列
void EnterQueue(struct queue *head,int x)
{
    printf(
"\n %d Enter queue.\n",x);
    
if(head->quelen==m)//队列 满
    {
        printf(
"queue is full.Enter queue,failed.\n");
        
return;
    }
    head
->seq[head->rear]=x;
    head
->rear=(head->rear+1)%m;
    head
->quelen++;
}
//出队列
void GoOutOfQueue(struct queue *head)
{
    
int front;
    
if(head->quelen==0)//队列 空
    {
        printf(
"queue is empty, go out of queue, failed.\n");
        
return;
    }
    
if(head->rear >= head->quelen)//第一种情况
        front=head->rear-head->quelen;
    
if(head->rear < head->quelen)//第二种情况
        front=head->rear+(m-head->quelen);
    printf(
"\n %d goes out of queue.\n",head->seq[front]);
    
    head
->quelen--;
}
//显示队列
void ShowQueue(struct queue *head)
{
    
    
int i;
    
int front;
    
if(head->quelen==0)
    {
        printf(
"\n queue is empty.\n");
        
return;
    }
    printf(
"\n Show queue elements:\n");
    
if(head->rear >= head->quelen)//第一种情况
    {
        front
=head->rear-head->quelen;
        
for(i=front;i<head->rear;i++)
            printf(
" %d ",head->seq[i]);
        printf(
"\n");
        
return;
    }
    
    
if(head->rear < head->quelen)//第二种情况
    {
        front
=head->rear+(m-head->quelen);
        
for(i=front;i<m;i++)
            printf(
" %d ",head->seq[i]);
        
for(i=0;i<head->rear;i++)
            printf(
" %d ",head->seq[i]);
    printf(
"\n");
    
return;
    }
    
}

void main()
{
    
int i;
    
struct queue * head;
    head
=initial();
    ShowQueue(head);
    
for(i=0;i<10;i++)
    {
        EnterQueue(head,i
+10);
        EnterQueue(head,i
+100);
        ShowQueue(head);
        GoOutOfQueue(head);
        ShowQueue(head);
    }
}


posted @   emanlee  阅读(303)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示