-1

文字を順番に出力するためにイテレーションにデキュー操作を入れたのはかなり奇妙ですが、失敗して最初の 2 文字のみを出力しましたが、イテレーションの外でこのデキュー操作を使用すると、問題ありません!

デキューを次のように定義します。

char *C_dequeue(struct COMMON_QUEUE *q) {
  if (C_get_queue_length(q)==0) {
    fprintf(stderr, "Linked queue is empty!!!");
    return NULL;
  }
  struct QUEUE_NODE *p;
  p = malloc(sizeof(struct QUEUE_NODE));
  if (p==NULL) {
    return NULL;
  }
  p = q->q_node;

  char *temp;
  temp = p->next->string;
  p = p->next;
  q->q_node->next = p->next;
  free(p);
  p->next = NULL;
  p->string = NULL;

  return temp;
}

main.c ファイルで使用します。

struct COMMON_QUEUE *test10;

test10 = C_init_queue();

C_enqueue(test10, "Someone ");
C_enqueue(test10, "like ");
C_enqueue(test10, "you!");

printf("length: %d\n", C_get_queue_length(test10));
int j;

/* it prints the first two characters */
for (j = 0; j <= C_get_queue_length(test10)+1; ++j) {
  printf("[%d %s]", j, C_dequeue(test10));
}
printf("\n");

/* it prints all the characers */
C_dequeue(test10);
C_dequeue(test10);
C_dequeue(test10);

C_destroy_queue(test10);

ばかげた間違いを犯した可能性があると思います!!!

4

1 に答える 1

1

C_get_queue_length(test10)+1 は、ループの反復ごとに評価されます。キューが短くなると、ある時点で j 未満になります。

これは 2 回目の繰り返しの後に発生し、ループが終了したと思われます。

「<=」と「+1」は、別の方法で問題を解決しようとしたように見えますが。

int len = C_get_queue_length(test10) ;
for ( j = 0 ; j < len ; j++) { ...}

あなたが欲しいものです

于 2013-11-12T11:26:24.017 に答える