制作队列程序

有人可以帮我制作一个队列程序。 我想在显示中将array[0]设置为array[1] ,但实际上我在array[0]处添加值。 我得到了如何运行add函数,但我无法执行将从ex查看的视图和删除命令。 array [0]到array [4],当数组[1]显示到数组[5]并插入值时。

 #include  #include  #define p printf #define s scanf int rear = 0; int front = 0; int *q_array = NULL; int size = 0; main() { int num, opt; char cont[] = { 'y' }; clrscr(); p("Queue Program\n\n"); p("Queue size: "); s("%d", &size); p("\n"); if(size > 0) { q_array = malloc(size * sizeof(int)); if(q_array == NULL) { p("ERROR: malloc() failed\n"); exit(2); } } else { p("ERROR: size should be positive integer\n"); exit(1); } while((cont[0] == 'y') || (cont[0] == 'Y')) { clrscr(); p("Queue Program"); p("\n\nQueue size: %d\n\n", size); p("MAIN MENU\n1. Add\n2. Delete\n3. View"); p("\n\nYour choice: "); s("%d", &opt); p("\n"); switch(opt) { case 1: if(rear==size) { p("You can't add more data"); } else { p("Enter data for Queue[%d]: ", rear+1); s("%d", &num); add(num); } break; case 2: delt(); break; case 3: view(); break; } p("\n\nDo you want to continue? (Y\/N)"); s("%s", &cont[0]); } } add(int a) { q_array[rear]=a; rear++; } delt() { if(front==rear) { p("Queue Empty"); } else { p("Queue[%d] = %d removed.", front, q_array[front]); front++; } } view() { int i; for(i=front;i<=rear;i++) p("\nQueue[%d] = %d", i, q_array[i]); } 

  1. 这里有一个严重的问题

     char cont[] = { 'y' }; ... s("%s", &cont[0]); 

    您只保留了一个字节,但scanf将写入至少2个字节,这意味着您将有一个缓冲区溢出,然后整体行为是不可预测的。 如果你想读取一个字符然后使用"%c"作为模式,但问题是字符将在缓冲区中进行下一次读取,因此你将不得不清除缓冲区。

    它更容易做到:

     char line[1024]; fgets(line, sizeof line, stdin); if(line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0; if(strcmp(line, "Y") == 0 || strcmp(line, "y")==0) 

    这是一个更多的代码,但这样更安全。

  2. 有许多队列,有fifo,lifo,并根据它你选择如何建立它

  3. 在处理队列时,最好使用pushpoptop等函数名,因为它们在其他程序员和队列库中被广泛使用。 请改用这些名称。

  4. 在您的情况下,相反,如果使用front记忆,则应使用memmove并使用变量len来计算节点中当前的元素数。 一旦你弹出一个元素,你就获得了更多元素的新空间。

此外,尝试使用更少的全局变量和更多的封装:(在我的示例中,我不会关心malloc返回NULL ,我想保持简短)

 #include  /* for size_t */ typefed struct { size_z len; size_z max_size; int *data; } queue; void queue_init(queue *q, size_t max_size) { q->len = 0; q->max_size = max_size; q->data = malloc(max_size * sizeof *(q->data)); /* this is a good trick! * If you need to change the datatype of 'data', * you only need to change the definition of it. * This code is valid for any type */ } int push(queue *q, int data) { if(q->len == q->max_size) return 0; /* not enough space */ q->data[q->len++] = data; return 1; } int top(queue *q, int *data) { if(q->len == 0) return 0; /* no elements in the queue */ *data = q->data[0]; return 1; } int pop(queue *q, int *data) { if(top(q, data) == 0) return 0; memmove(q->data, q->data + sizeof *(q->data), q->len--); return 1; } 

BTW:

 #define p printf #define s scanf 

就像Daniel Fischer所说,这很难看; 不要那样做。