相对而言,队列是比较简单的。
代码还有些warning,我改不动,要找gz帮忙。
1 #include <stdio.h> 2 3 typedef struct node 4 { 5 int data; 6 struct node* next; 7 }Node; 8 9 typedef struct queue 10 { 11 Node* head; 12 Node* tail; 13 }Queue; 14 15 void InitQueue(Queue*); 16 void EnQueue(Queue*, int); 17 int DeQueue(Queue* queue); 18 void PrintQueue(Queue* queue); 19 int IsNull(Queue* queue); 20 void DelQueue(Queue* queue); 21 22 void DelQueue(Queue* queue) 23 { 24 while(queue->head != queue->tail) 25 { 26 DeQueue(queue); 27 } 28 29 } 30 31 32 33 void PrintQueue(Queue* queue) 34 { 35 if(IsNull(queue)) 36 { 37 printf("empty queue. "); 38 return ; 39 } 40 Node* curNode= queue->head->next; 41 while(curNode) 42 { 43 if(curNode->next !=NULL) 44 { 45 printf("%d==>", curNode->data); 46 }else 47 { 48 printf("%d ", curNode->data); 49 50 } 51 curNode = curNode->next; 52 } 53 printf(" "); 54 55 } 56 57 58 void InitQueue(Queue* queue) 59 { 60 queue->tail = (Node*)malloc(sizeof(Node));//warning 61 queue->tail->data = -1; 62 queue->head = queue->tail; 63 queue->tail->next = NULL; 64 } 65 //入队列 66 void EnQueue(Queue* queue, int data) 67 { 68 Node * newNode = (Node*)malloc(sizeof(Node));//warning 69 newNode->data = data; 70 newNode->next = NULL; 71 queue->tail->next = newNode;//2b 这里漏了。。。导致链表连不上去 72 queue->tail = newNode; 73 } 74 75 int DeQueue(Queue* queue) 76 { 77 int popValue = queue->head->data; 78 Node *popNode = queue->head; 79 queue->head = queue->head->next; 80 free(popNode);//warning 81 return popValue; 82 } 83 //1 means Null 84 int IsNull(Queue* queue) 85 { 86 return (queue->head == queue->tail); 87 } 88 89 90 int main(void) 91 { 92 printf("Hello World! "); 93 Queue queue; 94 InitQueue(&queue); 95 //printf("IsNull = %d ", IsNull(&queue)); 96 printf("enque 4 times and the elems: 1, 2, 3, 4 "); 97 EnQueue(&queue,1); 98 //printf("IsNull = %d ", IsNull(&queue)); 99 EnQueue(&queue,2); 100 EnQueue(&queue,3); 101 EnQueue(&queue,4); 102 PrintQueue(&queue); 103 printf("deque 1 times. "); 104 DeQueue(&queue); 105 PrintQueue(&queue); 106 107 printf("IsNull = %d ", IsNull(&queue)); 108 DelQueue(&queue); 109 printf("IsNull = %d ", IsNull(&queue)); 110 111 return 0; 112 }
运行结果:
Hello World!
enque 4 times and the elems: 1, 2, 3, 4
1==>2==>3==>4
deque 1 times.
2==>3==>4
IsNull = 0
IsNull = 1 ////1 means Null
下个先写写排序吧,上次写了一部分,当然算法思想是参考其他人,我只是一个重造的菜狗。菜狗,菜狗,菜狗。。。,明天回家,很开心。晚上吃的太多,有点难受,@2016年7月29日00:44:26,睡不着。。。