链式队列

 1 #include <cstdio>
 2 #include <conio.h>
 3 #include <windows.h>
 4 typedef char ElemType;
 5 
 6 typedef struct QNode
 7 {
 8    ElemType data;
 9    struct QNode *next;   
10 }QNode,*QueuePtr;
11 
12 typedef struct
13 {
14    QueuePtr front;   //队头指针 
15    QueuePtr rear;    //队尾指针 
16 }LinkQueue;
17 
18 //创建一个队列 
19 void initQueue(LinkQueue *q)
20 {
21    q->front = q->rear = (QueuePtr)malloc(sizeof(QNode));    //初始化一个空队列
22    if(!q->front)  exit(0);
23    q->front->next = NULL;   //头指针置NULL 
24 }
25 
26 //入队列
27 void EnQueue(LinkQueue *q,ElemType e)
28 {
29    QueuePtr p;
30    p = (QueuePtr)malloc(sizeof(QNode));   //创建一个队列元素结点 
31    if(!q->front)  exit(0);
32    p->data = e;
33    p->next = NULL;
34    q->rear->next = p;   //原本的队尾next指针指向新的结点 
35    q->rear = p;         //插入数据 
36 }
37 
38 //出队列
39 void DeQueue(LinkQueue *q,ElemType *e)
40 {
41    QueuePtr p;
42    if(q->front == q->rear) return;  //队列空,返回 
43    p = q->front->next;
44    *e = p->data;
45    q->front->next = p->next;
46    if(q->rear == p)  q->rear = q->front;  //如果队头就是队尾,则修改队尾指针 
47    free(p);   
48 }
49 
50 //销毁一个队列
51 void DestroyQueue(LinkQueue *q)
52 {
53    while(q->front)
54       {
55          q->rear = q->front->next;
56          free(q->front);
57          q->front = q->rear;   
58       }   
59 } 
60 
61 int main()
62 {
63    ElemType e;
64    LinkQueue q;
65    initQueue(&q);    //初始化队列 
66    printf("Please input a string into a queue\n");
67    scanf("%c",&e);
68    while(e!='@')
69       {
70          EnQueue(&q,e);    //向队列输入 
71          scanf("%c",&e);   
72       }
73    printf("The string into the queue is\n");
74    while(q.front != q.rear)   //出列 
75       {
76          DeQueue(&q,&e);
77          printf("%c",e);   
78       }
79    printf("\n");
80    system("pause>nul");
81    return 0;
82 }

 

posted @ 2013-06-15 23:09  瓶哥  Views(319)  Comments(0Edit  收藏  举报