- #include <iostream>
- using namespace std;
- struct Node
- {
- int id;
- int childNum;
- Node* childList[10];
- };
- struct Queue
- {
- Node* list[100];
- int front;
- int rear;
- int num;
- };
- void InitQueue(Queue &q)
- {
- q.front = q.rear = 99;
- q.num = 0;
- }
- int EnQueue(Queue &q,Node* n)
- {
- if (q.num == 100) return -1;
- q.rear = (q.rear+1)%100;
- q.list[q.rear] = n;
- q.num = q.num+1;
- return 1;
- }
- int DeQueue(Queue &q,Node* &n)
- {
- if (q.num == 0) return -1;
- q.front = (q.front+1)%100;
- n = q.list[q.front];
- q.num = q.num-1;
- return 1;
- }
- int main()
- {
- int i;
- Node* tree;
- tree = (Node*)malloc(sizeof(Node));
- tree->id = 1;
- tree->childNum = 3;
- for (i=1;i<=tree->childNum;i++)
- {
- tree->childList[i-1] = (Node*)malloc(sizeof(Node));
- tree->childList[i-1]->id = i+1;
- tree->childList[i-1]->childNum = 0;
- }
- tree->childList[0]->childNum = 2;
- tree->childList[0]->childList[0] = (Node*)malloc(sizeof(Node));
- tree->childList[0]->childList[0]->id = 5;
- tree->childList[0]->childList[0]->childNum = 0;
- tree->childList[0]->childList[1] = (Node*)malloc(sizeof(Node));
- tree->childList[0]->childList[1]->id = 6;
- tree->childList[0]->childList[1]->childNum = 0;
- Queue q;
- InitQueue(q);
- EnQueue(q,tree);
- while(q.num!=0)
- {
- Node* n;
- DeQueue(q,n);
- cout<<n->id<<' ';
- if (n->childNum!=0)
- {
- for (i=0;i<n->childNum;i++) EnQueue(q,n->childList[i]);
- }
- }
- cout<<endl;
- return 0;
- }
输出为:1 2 3 4 5 6