天天看點

42深入了解C指針之---指針與隊列

深入了解C指針之---指針與隊列

一、借助第40指針與連結清單的相關内容,稍微修改即可:

   1、定義頭檔案queue.h代碼如下:

1 #include <stdlib.h>
 2 #include <stdio.h>
 3
 4 #ifndef queue_h
 5 #define queue_h
 6 typedef int DataType;
 7
 8 typedef struct _node{
 9     DataType data;
10     struct _node *next;
11 } Node;
12
13 typedef struct _queue{
14     Node *head;
15     Node *tail;
16 } Queue;
17
18 void initQueue(Queue *);
19 void enQueue(Queue *, DataType);
20 void deQueue(Queue *);
21 int getLength(Queue *);
22 void dispQueue(Queue *);
23
24 #endif      

  頭檔案中依舊是完成資料類型的聲明和資料的操作函數的聲明。

   2、頭檔案對應的實作檔案queue.c代碼如下:

1 #include "queue.h"
 2
 3 //隊列初始化
 4 void initQueue(Queue *queue){
 5     queue->head = NULL;
 6     queue->tail = NULL;
 7 }
 8
 9 //隊列入
10 void enQueue(Queue *queue, DataType iData){
11     Node *node = (Node *)malloc(sizeof(Node));
12     node->data = iData;
13     node->next = NULL;
14
15     if(queue->head == NULL){
16         queue->head = node;
17     }else{
18         queue->tail->next = node;
19     }
20     queue->tail = node;
21
22     return;
23
24 }
25
26 //隊列出
27 void deQueue(Queue *queue){
28     if(queue->head->next == NULL){
29         queue->head = NULL;;
30     }else{
31         queue->head = queue->head->next;
32     }
33
34     return;
35 }
36
37 //隊列長度
38 int getLength(Queue *queue){
39     Node *node = queue->head;
40     int i = 0;
41     while(node != NULL){
42         node = node->next;
43         i++;
44     }
45
46     return i;
47 }
48
49 //隊列輸出
50 void dispQueue(Queue *queue){
51     Node *node = queue->head;
52     int i = 0;
53     while(node != NULL){
54         printf("the %dth node: %d\n", i + 1, node->data);
55         node = node->next;
56         i++;
57     }
58     printf("disp finished!\n");
59
60     return;
61 }      

  代碼說明:

    1、入隊函數使用連結清單的尾插法

1 #include "queue.h"
 2
 3 int main(int argc, char **argv)
 4 {
 5     Queue *queue1 = (Queue *)malloc(sizeof(Queue));
 6     printf("the first:\n");
 7     initQueue(queue1);
 8     enQueue(queue1, 1);
 9     enQueue(queue1, 3);
10     enQueue(queue1, 5);
11     enQueue(queue1, 7);
12     enQueue(queue1, 9);
13     printf("The length: %d\n", getLength(queue1));
14     dispQueue(queue1);
15     printf("the second:\n");
16     deQueue(queue1);
17     printf("The length: %d\n", getLength(queue1));
18     dispQueue(queue1);
19     deQueue(queue1);
20     dispQueue(queue1);
21     printf("The length: %d\n", getLength(queue1));
22     enQueue(queue1, 11);
23     dispQueue(queue1);
24     printf("The length: %d\n", getLength(queue1));
25
26     return 0;
27 }      

人就像是被蒙着眼推磨的驢子,生活就像一條鞭子;當鞭子抽到你背上時,你就隻能一直往前走,雖然連你也不知道要走到什麼時候為止,便一直這麼堅持着。