两个栈模拟一个队列,主函数中应输出第一个入队的元素,实际上输出的是第二个,即数字2.问题出在哪里?如何纠正?
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack
{
int* Data;
int size;//有效元素个数
int capacity;//栈的容量
}Stack;
typedef struct Queue
{
Stack input;
Stack output;
//有效元素个数
int size;
}Queue;
void StackInit(Stack* stack,int capacity)//栈初始化
{
if (stack)
{
stack->capacity = capacity;
stack->size = 0;
stack->Data = (int*)malloc(sizeof(int)* stack->capacity);
}
}
int StackEmpty(Stack* stack)//判栈空
{
if (stack->size == 0)
{
return 1;
}
else
{
return 0;
}
}
int StackGetTop(Stack* stack)//取栈顶元素
{
if (stack == NULL)
{
return -1;
}
if (stack->size == 0)
{
return 0;
}
else
{
return stack->Data[stack->size];
}
}
int StackPush(Stack* stack,int value)//入栈
{
if (stack == NULL)
{
return 0;
}
else
{
stack->Data[stack->size] = value;
stack->size++;
return 1;
}
}
int StackPop(Stack* stack)//出栈
{
if (stack == NULL)
{
return -1;
}
if(stack->size == 0)
{
return 0;
}
else
{
stack->size--;
return stack->Data[stack->size];
}
}
void QueueInit(Queue* queue,int capacity)//队列初始化
{
if (queue)
{
StackInit(&queue->input,capacity);
StackInit(&queue->output, capacity);
queue->size = 0;
}
}
void QueuePush(Queue *queue, int value)//入队
{
if (queue)
{
StackPush(&queue->input, value);
queue->size++;
}
}
//取队首元素函数
int QueueFront(Queue* queue)
{
if (queue == NULL)
{
return -1;
}
if (StackEmpty(&queue->output))
{
if (StackEmpty(&queue->input))
{
return 0;
}
else
{
int newsize = queue->input.size;
for (int i = 0; i <newsize ; ++i)
{
int tmp = StackGetTop(&queue->input);
StackPop(&queue->input);
StackPush(&queue->output, tmp);
}
}
}
return StackGetTop(&queue->output);
}
int QueuePop(Queue* queue)//出队
{
if (queue == NULL)
{
return -1;
}
if (StackEmpty(&queue->output))
{
if (StackEmpty(&queue->input))
{
return 0;
}
else
{
int newsize = queue->input.size;
for(int i = 0;i< newsize;++i)
{
int tmp = StackGetTop(&queue->input);
StackPop(&queue->input);
StackPush(&queue->output,tmp);
}
}
}
StackPop(&queue->output);
queue->size--;
return 1;
}
int main()
{
Queue queue;
QueueInit(&queue,10);
//入队列函数测试
QueuePush(&queue, 1);
QueuePush(&queue, 2);
QueuePush(&queue, 3);
QueuePush(&queue, 4);
QueuePop(&queue);
int a = QueueFront(&queue);
printf("%d \n", a);
system("pause");
return 0;
}