队列的数组实现
2015-09-23 14:09
375 查看
声明 curosr_queue.h:
实现 implementation.c:
测试 main.c:
#ifndef CURSOR_QUEUE_H_INCLUDED #define CURSOR_QUEUE_H_INCLUDED struct QueueRecord; typedef struct QueueRecord *Queue; int IsEmpty(Queue Q); int IsFull(Queue Q); Queue CreateQueue(int MaxElements); void DisposeQueue(Queue Q); void MakeEmpty(Queue Q); void Enqueue(int X, Queue Q); int Front(Queue Q); int Dequeue(Queue Q); int FrontAndDequeue(Queue Q); #endif // CURSOR_QUEUE_H_INCLUDED
实现 implementation.c:
#include<stdio.h> #include "cursor_queue.h" #define MinQueueSize 5 struct QueueRecord{ int Capacity; int Front; int Rear; int Size; int *Array; }; int IsEmpty(Queue Q){ return Q->Size == 0; } Queue CreateQueue(int MaxElements) { Queue Q; if(MaxElements < MinQueueSize) printf("Too small queue size!"); Q = malloc(sizeof(struct QueueRecord)); if(Q == NULL) { printf("Out of space!"); } Q->Array = malloc(sizeof(int) * MaxElements); if(Q->Array == NULL){ printf("Out of space!"); } MakeEmpty(Q); Q->Capacity = MaxElements; return Q; } void MakeEmpty(Queue Q) { Q->Rear = 0; Q->Front = 1; Q->Size = 0; } static int Succ(int Value, Queue Q) { if(++Value == Q->Capacity) Value = 0; return Value; } int IsFull(Queue Q) { return Q->Size == Q->Capacity; } void Enqueue(int X, Queue Q) { if(IsFull(Q)) printf("Error! Full Queue!\n"); else{ Q->Size++; Q->Rear = Succ(Q->Rear, Q); Q->Array[Q->Rear] = X; } } int Dequeue(Queue Q){ int Data; if(IsEmpty(Q)){ printf("Error, empty queue!"); return -1; } else{ Q->Size--; Data = Q->Array[Q->Front]; Q->Front = Succ(Q->Front, Q); } return Data; } void DisposeQueue(Queue Q) { free(Q->Array); free(Q); }
测试 main.c:
#include <stdio.h> #include <stdlib.h> #include "cursor_queue.h" int main() { Queue Q; Q = CreateQueue(10); int i = 0; for(i = 0; i < 10; i++) Enqueue(i ,Q); Enqueue(10, Q); for(i = 0; i < 10; i++) printf("%d ", Dequeue(Q)); printf("\n"); DisposeQueue(Q); Q = CreateQueue(10); for(i = 0; i < 10; i++) printf("%d\n", Dequeue(Q)); return 0; }
相关文章推荐
- ASP.NET 数据库页面访问简单工具
- javascript js保留小数位数的方法
- 如何采用不加锁的方式实现线程同步
- 如何采用不加锁的方式实现线程同步
- TSM 修改control path
- IEtester从重要变鸡肋
- sscanf(), sscanf_s()
- BST、B树、B-树、B+树、B*树
- oracle备份还原
- 第二次作业:个人项目实践
- Great StackOverflow questions
- SQLSERVER 分区分表
- 8种排序
- 小强的HTML5移动开发之路(13)——HTML5中的全局属性
- Myeclipse Source not found 以及 调用javadoc的问题
- 小强的HTML5移动开发之路(13)——HTML5中的全局属性
- 小强的HTML5移动开发之路(13)——HTML5中的全局属性
- Java并发
- thinkphp中ajax用户名校验
- 图片上传安全性问题,根据ContentType (MIME) 判断其实不准确、不安全