2008秋季-计算机软件基础-0917课堂用例(2)

循环队列

 参见:http://www.cnblogs.com/emanlee/archive/2007/09/17/895463.html

#include < stdlib.h >
// 定义队列的结构
struct  queue
{
   
int  q[ 4 ]; // 存放数据元素
    int  front; // 队头指针,指向队头
    int  rear; // 队尾指针,队尾指针始终指向队尾元素的后一个位置
};
// 初始化队列
struct  queue  *  InitialQueue()
{
 
struct  queue  *  head;
 head
= ( struct  queue  * )
     malloc(
sizeof struct  queue ));
 head
-> front = 0 ;
 head
-> rear = 0 ;
 
return  head;
}

void  EnterIntoQueue( struct  queue  *  head,
                    
int  value)
{
    
if (head -> front ==  (head -> rear + 1 ) % 4 )
    {
       printf(
" Queue is full. Enter failed.\n " );
        
return ;
    }
    head
-> q[head -> rear] = value;
    head
-> rear = ( head -> rear + 1 ) % 4 ;
 }

void  DeleteFromQueue( struct  queue  *  head)
{
 
if (head -> front == head -> rear)
 {
     printf(
" Queue is empty, Delete failed\n " );
 }
 
else
    {
        head
-> front = (head -> front + 1 ) % 4 ;
    }
}

void  ShowQueue( struct  queue  *  head)
{
/*  输出要分开设计  */
  
int  i;
  printf(
" \n队列元素\n " );
  
for (i = 0 ;i <= 3 ;i ++ )
      printf(
"  %d  " ,head -> q[i]);
}

void  main()
{

 
struct  queue  *  head;
 head
= InitialQueue();
 EnterIntoQueue(head,
1 );
 ShowQueue(head);
 EnterIntoQueue(head,
2 );
 ShowQueue(head);
}

你可能感兴趣的:(2008)