SquenceQueue by c

 1 #pragma once
 2 
 3 #define MAX_LINE 100
 4 
 5 typedef enum {false, true} bool;
 6 typedef char *SQElemType;
 7 
 8 typedef struct {
 9     int front;
10     int rear;
11     SQElemType *data;
12 } SQueue, *SQueuePtr;
13 
14 bool CreateSQueue(SQueuePtr p);
15 void DestroySQueue(SQueuePtr p);
16 bool EnSQueue(SQueuePtr p, SQElemType d);
17 bool DeSQueue(SQueuePtr p, SQElemType *d);
18 int GetLength(SQueuePtr);
 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include "SQueue.h"
 4 
 5 bool CreateSQueue(SQueuePtr p)
 6 {
 7    p->data = (SQElemType *)malloc(sizeof(*p->data) * MAX_LINE);
 8     if (NULL == p->data)
 9     return false;
10 
11     p->rear = 0;
12     p->front = 0;
13 
14     return true;
15 }
16 
17 void DestroySQueue(SQueuePtr p)
18 {
19     free(p->data);
20 }
21 
22 static bool IsEmpty(SQueuePtr p)
23 {
24     return p->front == p->rear;
25 }
26 
27 static bool IsFull(SQueuePtr p)
28 {
29     return (p->rear + 1) % MAX_LINE == p->front;
30 }
31 
32 bool EnSQueue(SQueuePtr p, SQElemType d)
33 {
34     if (IsFull(p))
35     return false;
36 
37     p->data[p->rear] = d;
38     p->rear = (p->rear + 1) % MAX_LINE;
39 
40     return true;
41 }
42 
43 bool DeSQueue(SQueuePtr p, SQElemType *d)
44 {
45     if (IsEmpty(p))
46     return false;
47 
48     *d = p->data[p->front];
49     p->front = (p->front + 1) % MAX_LINE;
50 
51     return true;
52 }
53 
54 int GetLength(SQueuePtr p)
55 {
56     return (p->rear - p->front + MAX_LINE) % MAX_LINE;
57 }
 1 #include <stdio.h>
 2 #include "SQueue.h"
 3 
 4 int main(int argc, char **argv)
 5 {
 6     int i = 0;
 7     SQElemType d;
 8     SQueue p;
 9     SQElemType data[] = {"hello", "world"};
10 
11     CreateSQueue(&p);
12 
13     while (i < 2)
14     EnSQueue(&p, data[i++]);
15 
16     printf("Init :length = %d\n", GetLength(&p));
17 
18     while (DeSQueue(&p, &d))
19     printf("%s length = %d\n", d, GetLength(&p));
20 
21     DestroySQueue(&p);
22 
23     return 0;
24 }

posted on 2012-09-02 11:34  robin.he  阅读(138)  评论(0)    收藏  举报

导航