使用队列进行数据分类
Posted zhangleshan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用队列进行数据分类相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdbool.h> 4 #include <time.h> 5 #include "Queue.h" 6 7 void fillQueues(QUEUE*, QUEUE*, QUEUE*, QUEUE*); 8 void printQueues(QUEUE*, QUEUE*, QUEUE*, QUEUE*); 9 10 void printOneQueue(QUEUE* pQueue); 11 12 int main() 13 { 14 QUEUE* q0to9; 15 QUEUE* q10to19; 16 QUEUE* q20to29; 17 QUEUE* qOver29; 18 19 printf("Welcome to a demonstration of categorizing data. " 20 "We generate 25 random numbers and then group them " 21 "into categories using queues. "); 22 23 q0to9 = createQueue(); 24 q10to19 = createQueue(); 25 q20to29 = createQueue(); 26 qOver29 = createQueue(); 27 28 fillQueues(q0to9, q10to19, q20to29, qOver29); 29 printQueues(q0to9, q10to19, q20to29, qOver29); 30 31 return 0; 32 } 33 34 void fillQueues(QUEUE* q0to9, QUEUE* q10to19, QUEUE* q20to29, QUEUE* qOver29) 35 { 36 int category; 37 int item; 38 int* dataPtr; 39 40 printf("Categorizing data: "); 41 srand(time(0)); 42 43 for(int i = 1; i <= 25; i++){ 44 if(!(dataPtr = (int*)malloc(sizeof(int)))) 45 printf("Overflow in fillQueuesa "), exit(100); 46 47 *dataPtr = item = rand() % 51; 48 category = item / 10; 49 printf("%3d", item); 50 if(!(i % 11)) 51 printf(" "); 52 53 switch(category){ 54 case 0 : enqueue(q0to9, dataPtr); 55 break; 56 case 1 : enqueue(q10to19, dataPtr); 57 break; 58 case 2 : enqueue(q20to29, dataPtr); 59 break; 60 default: enqueue(qOver29, dataPtr); 61 break; 62 } 63 } 64 printf(" End of data categorization "); 65 return; 66 } 67 void printQueues(QUEUE* q0to9, QUEUE* q10to19, QUEUE* q20to29, QUEUE* qOver29) 68 { 69 printf("Data 0.. 9: "); 70 printOneQueue(q0to9); 71 72 printf("Data 10.. 19: "); 73 printOneQueue(q10to19); 74 75 printf("Data 20.. 29: "); 76 printOneQueue(q20to29); 77 78 printf("Data Over 29: "); 79 printOneQueue(qOver29); 80 81 return; 82 } 83 84 void printOneQueue(QUEUE* pQueue) 85 { 86 int lineCount; 87 int* dataPtr; 88 89 lineCount = 0; 90 while(!emptyQueue(pQueue)){ 91 dequeue(pQueue, (void*)&dataPtr); 92 if(lineCount++ >= 10){ 93 lineCount = 1; 94 printf(" "); 95 } 96 printf("%3d", *dataPtr); 97 } 98 printf(" "); 99 100 return; 101 }
以上是关于使用队列进行数据分类的主要内容,如果未能解决你的问题,请参考以下文章