谁能帮我做一个队列程序。我想将 array[0]
设置为 array[1]
只是在显示中,但实际上我在 array[0]
。我知道如何运行添加功能,但我不能执行将从 ex 查看的查看和删除命令。 array[0] 到 array[4],当显示 array[1] 到 array[5] 时插入值。
#include <stdio.h>
#include <stdlib.h>
#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]);
}
最佳答案
这里有一个严重的问题是
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)
代码有点多,但这样更安全。
有很多队列,有fifo,lifo,根据它选择如何构建它
在处理队列时,最好使用
push
、pop
和top
等函数名,因为它们在队列中被广泛使用其他程序员和队列库。使用 这些名称。在你的情况下,如果记住
front
和rear
你应该使用memmove
并使用变量len
来计算当前的数量 节点中的元素。一旦你弹出一个元素,你就获得了新的空间 更多元素。
此外,尝试使用更少的全局变量和更多的封装:(在我的例子中我是
不会关心 malloc
返回 NULL
,我想保持简短)
#include <string.h> /* 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;
}
顺便说一句:
#define p printf
#define s scanf
正如 Daniel Fischer 所说,这很丑;不要那样做。
关于c - 制作队列程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12652918/