c/c++语言开发共享制作队列程序

有人可以帮我制作一个队列程序。 我想在显示中将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 Programnn"); p("Queue size: "); s("%d", &size); p("n"); if(size > 0) { q_array = malloc(size * sizeof(int)); if(q_array == NULL) { p("ERROR: malloc() failedn"); exit(2); } } else { p("ERROR: size should be positive integern"); exit(1); } while((cont[0] == 'y') || (cont[0] == 'Y')) { clrscr(); p("Queue Program"); p("nnQueue size: %dnn", size); p("MAIN MENUn1. Addn2. Deleten3. View"); p("nnYour 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("nnDo 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]); } 

    此外,尝试使用更少的全局变量和更多的封装:(在我的示例中,我不会关心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所说,这很难看; 不要那样做。

      以上就是c/c++开发分享制作队列程序相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519694.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐