/** * 删除元素并返回 */ ElementType DeleteQ(Queue *q) { ElementType e; if (IsEmptyQ(q)) { printf("队列已空\r\n"); e = -1; } else{ e = q->data[q->front % MaxSize]; q->front++; } return e; }
void AddQ(Queue * PtrQ,QueueElem item){ // if( !IsFullQ(PtrQ) ){ //无法简单判断是否已满,省去该步骤 QNode * t = (QNode*)malloc(sizeof(QNode)); t->Data = item; t->Next = NULL; if( IsEmptyQ(PtrQ) ){ PtrQ->front = PtrQ->rear = t; PtrQ->front->Next = PtrQ->rear->Next = t; }else{ PtrQ->rear->Next = t; PtrQ->rear = t; } // }else{ // printf("Queue Full \n"); // } return ; }
void BFS(int i) { G->Visited[i] = 1; printf("%d ", i); AddQ(Q, i); while (!IsEmptyQ(Q)) { int j = DeleteQ(Q); int k; for (k = 0; k < G->n; k++) { if (!G->Visited[k] && G->Edges[j][k]) { G->Visited[k] = 1; printf("%d ", k); AddQ(Q, k); } } } }
QueueElem DeleteQ(Queue * PtrQ){ if( !IsEmptyQ(PtrQ) ){ QNode * FrontCell; QueueElem FrontElem; FrontCell = PtrQ->front; FrontElem = FrontCell->Data; if( PtrQ->front == PtrQ->rear ){ //只有一个元素 PtrQ->front = PtrQ->rear = NULL; //队列置为空 }else{ PtrQ->front = PtrQ->front->Next; } free(FrontCell); return FrontElem; }else{ printf("Queue Empty \n"); return 0; } }