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的数据挨个取出来放到stack2
while (!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;
}
【leetcode】232. 用栈实现队列
最新推荐文章于 2024-07-31 22:38:43 发布
本文介绍了如何使用两个栈(stack1和stack2)模拟一个队列的功能,包括创建、入队、出队、查看队头和检查队列是否为空的操作。作者详细展示了MyQueue结构体的定义与相关函数实现。
摘要由CSDN通过智能技术生成