码迷,mamicode.com
首页 > 其他好文 > 详细

队列实现

时间:2017-12-03 20:52:55      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:color   void   tchar   str   getchar   clu   err   print   ...   

 1 #include "stdio.h"  
 2 #include "stdlib.h"  
 3 
 4 #define OK 1  
 5 #define ERROR 0  
 6 #define OVERFLOW -2  
 7 
 8 typedef char elemType;
 9 typedef struct _QNode{
10     elemType data;
11     struct _QNode *next;
12 }QNode;
13 typedef struct{
14     QNode *front;
15     QNode *rear;
16 }LinkQueue;
17 
18 int InitQueue(LinkQueue *q){
19     q->front = q->rear = (QNode *)malloc(sizeof(QNode));
20     if(!q->front)
21         exit(OVERFLOW);
22     q->front->next = NULL;
23     return OK;    
24 }
25 
26 int DestroyQueue(LinkQueue *q){
27     while(q->front){
28         q->rear = q->front->next;
29         free(q->front);
30         q->front = q->rear;
31     }
32     return OK;
33 }
34 
35 int EnQueue(LinkQueue *q,elemType e){
36     QNode *p = (QNode *)malloc(sizeof(QNode));
37     if(!p)
38         exit(OVERFLOW);
39     p->data = e;
40     p->next = NULL;
41     q->rear->next = p;
42     q->rear = p;  //将p插在队尾之后让p成为rear
43     return OK;
44 }
45 
46 int DeQueue(LinkQueue *q){
47     QNode *p = q->front->next;
48     if(q->front == q->rear)
49         return ERROR;
50     printf("已删除队头元素%c\n",p->data);
51     q->front->next = p->next;
52     if(q->rear == p)
53         q->rear = q->front;
54     return OK;
55 }
56 
57 void TraverseQueue(LinkQueue *q){
58     QNode *p = q->front->next;
59     if(q->front == q->rear)
60         printf("队列为空!\n");
61     else{
62         printf("队列中的元素为:\n");
63         while(p != q->rear){
64             printf(" %c",p->data);
65             p = p->next;
66         }
67         printf(" %c",q->rear->data);
68         printf("\n");
69     }
70 }
71 
72 void main(){  
73     LinkQueue *q = (LinkQueue *)malloc(sizeof(LinkQueue));  
74     InitQueue(q);  
75     TraverseQueue(q);  
76     printf("队尾插入元素.....\n");  
77     EnQueue(q,a);  
78     EnQueue(q,b);  
79     EnQueue(q,c);  
80     EnQueue(q,d);  
81     TraverseQueue(q);  
82     printf("删除队首元素...\n");  
83     DeQueue(q);  
84     TraverseQueue(q);  
85     getchar();
86 }  

 

队列实现

标签:color   void   tchar   str   getchar   clu   err   print   ...   

原文地址:http://www.cnblogs.com/ixummer/p/7967022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!