浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

基于数组的队列实现(C语言) - ahljjun的专栏 - 博客频道 - CSDN.NET

基于数组的队列实现(C语言)

分类: 算法与数据结构 371人阅读 评论(0) 收藏 举报

 

 

/*****************************************

                  接口文件QUEUE.h

****************************************/

 

#ifndef _QUEUE_H
#define _QUEUE_H

#ifndef BOOL
#define BOOL int
#endif

typedef int Item;
struct _Queue;
typedef struct _Queue  Queue;

typedef Queue* hQueue;//handle to Queue

hQueue Queue_Init(int nMax);

void Queue_Destroy(hQueue q);

void Queue_Put(hQueue q, Item elem);

Item Queue_Get(hQueue q);

int Queue_Size(hQueue q);

BOOL Queue_IsEmpty(hQueue q);
BOOL Queue_IsFull(hQueue q);

 


#endif

 

/*******************************

         实现文件QUEUE.c

*******************************/

 

#include<stdio.h>
#include<stdlib.h>
#include"QUEUE.h"

void Error(char* msg)
{
 printf("Error:%s",msg);
}


//机遇数组的队列实现
struct _Queue
{
 Item* elem;
 int head,tail;
 int N;
};

hQueue Queue_Init(int nMax)
{
 hQueue que=malloc(sizeof(*que));
 que->elem=malloc((nMax+1)*sizeof(*que->elem));
 que->head=que->tail=0;
 que->N=nMax+1;
 return que;
}


void Queue_Destroy(hQueue que)
{
 if(que->elem)
  free(que->elem);
 que->elem=NULL;
 free(que);
 que=NULL;

}

void Queue_Put(hQueue que, Item elem)
{
 if(Queue_IsFull(que))
 {
  Error("The Queue Is Full!/n");
  exit(-1);
 }
 que->elem[que->tail]=elem;
 que->tail=(que->tail+1)%(que->N);
}

Item Queue_Get(hQueue que)
{
 Item elem;
 if(Queue_IsEmpty(que))
 {
  Error("The Queue Is Empty!/n");
  exit(-1);
 }
 elem=que->elem[que->head];
 que->head=(que->head+1)%(que->N);
 return elem;
}

int Queue_Size(hQueue que)
{
 return (que->tail-que->head+que->N)%(que->N);
}

 

BOOL Queue_IsEmpty(hQueue que)
{
 return (que->head==que->tail);
}


BOOL Queue_IsFull(hQueue que)
{
 return (que->head==(que->tail+1)%(que->N));
}

 

 

/******************************

                   测试文件main.c

********************************/

 

#include<stdio.h>
#include<stdlib.h>
#include"QUEUE.h"


int main()
{
 hQueue  q=Queue_Init(7);
 int t=7;
 while(t)
 Queue_Put(q,t--);

 printf("Queue:%d/n",Queue_Get(q));
 printf("Queue:%d/n",Queue_Get(q));
 printf("Queue:%d/n",Queue_Get(q));

 printf("Queu Size= %d/n",Queue_Size(q));
 
printf("******************************************/n");
 t=30;
 Queue_Put(q,t--);
 Queue_Put(q,t--);

 printf("Queu Size= %d/n",Queue_Size(q));

 

 while(!Queue_IsEmpty(q))
 printf("Queue:%d/n",Queue_Get(q));
 Queue_Destroy(q);


 return 0;
}

 

 

 

 

posted on 2013-05-05 09:25  lexus  阅读(250)  评论(0编辑  收藏  举报