定义队列结构
typedef struct QUEUE
{
int *array;
int front;
int rear;
}Q;
建立队列
Q* creatqueue(int len)
{
Q* que = (Q*)malloc(sizeof(Q));
if (que)
{
que->array = (int*)malloc(sizeof(int) * len);
if (que->array == NULL)
return NULL;
que->front = que->rear = 0;
}
return que;
}
入队
int in(Q* que,int data,int len)
{
if (que->rear == len)
return 0;
que->array[++que->rear] = data;
return que->rear;
}
出队
int out(Q* que)
{
if (que->front != que->rear)
{
return que->array[++que->front];
que->array[que->front] = 0;
}
else return NULL;
}
主函数
void main()
{
int len, n, data;
printf("请输入队列最大长度:\n");
scanf_s("%d", &len);
Q* que=creatqueue(len);
printf("请输入入队元素个数:\n");
scanf_s("%d", &n);
printf("请输入入队元素:\n");
for (int i = 0; i < n; i++)
{
scanf_s("%d", &data);
if (in(que, data, len) == 0)
break;
}
//入队↑,出队↓
printf("请输入出队元素个数:");
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
{
if(data=out(que))
printf("%d ",data);
}
}
|