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 @ 2007-10-16 23:04  emanlee  阅读(302)  评论(0编辑  收藏  举报