用栈实现队列 题目链接
typedef int valuetype;
typedef struct {valuetype* arr;int top;int capacity;
} Stack;void Init(Stack* stack);void Push(Stack* stack, valuetype value);
void Pop(Stack* stack);valuetype Top(Stack* stack);
int Size(Stack* stack);
bool Empty(Stack* stack);void Destroy(Stack* stack);// 和上面图写的不一样,这里Stack不是指针
typedef struct {Stack stack1; // 存Stack stack2; // 取
} MyQueue;MyQueue* myQueueCreate() {MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));Init(&queue->stack1);Init(&queue->stack2);return queue;
}void myQueuePush(MyQueue* obj, int x) {assert(obj);Push(&obj->stack1, x);
}int myQueuePop(MyQueue* obj) {assert(obj);int top = myQueuePeek(obj);Pop(&obj->stack2);return top;
}int myQueuePeek(MyQueue* obj) {assert(obj);if (Empty(&obj->stack2)) {// 把stack1的数据挨个取出来放到stack2while (!Empty(&obj->stack1)) {Push(&obj->stack2, Top(&obj->stack1));Pop(&obj->stack1);}} // 从stack2取队头数据return Top(&obj->stack2);
}bool myQueueEmpty(MyQueue* obj) {assert(obj);return Empty(&obj->stack1) && Empty(&obj->stack2);
}void myQueueFree(MyQueue* obj) {assert(obj);Destroy(&obj->stack1);Destroy(&obj->stack2);free(obj);
}/*** Your MyQueue struct will be instantiated and called as such:* MyQueue* obj = myQueueCreate();* myQueuePush(obj, x);* int param_2 = myQueuePop(obj);* int param_3 = myQueuePeek(obj);* bool param_4 = myQueueEmpty(obj);* myQueueFree(obj);
*/void Init(Stack* stack) {assert(stack);stack->arr = NULL;stack->capacity = stack->top = 0;
}void Push(Stack* stack, valuetype value) {assert(stack);if (stack->top == stack->capacity) {stack->capacity = stack->capacity == 0 ? 10 : (int)(stack->capacity * 1.5);stack->arr = (valuetype*)realloc(stack->arr, sizeof(valuetype) * stack->capacity);if (stack->arr == NULL) {perror("realloc failed in the function Push(Stack*, valuetype).");return;}}stack->arr[stack->top++] = value;
}void Pop(Stack* stack) {assert(stack && stack->top > 0);stack->top--;
}valuetype Top(Stack* stack) {assert(stack && stack->top > 0);return stack->arr[stack->top - 1];
}int Size(Stack* stack) {assert(stack);return stack->top;
}bool Empty(Stack* stack) {assert(stack);return stack->top == 0;
}void Destroy(Stack* stack) {assert(stack);free(stack->arr);stack->arr = NULL;stack->capacity = stack->top = 0;
}