225. 用队列实现栈
解题思路
- push操作是直接把元素放入队列里面
- pop操作时把队列头的元素放入到队列尾,重复队列元素个数减一次
- top操作就是pop加push操作
代码实现
typedef struct {
int q[1001];
int l;
int r;
} MyStack;
MyStack* myStackCreate() {
MyStack* ans = (MyStack*)malloc(sizeof(MyStack));
ans -> r = ans -> l = 0;
return ans;
}
void myStackPush(MyStack* obj, int x) {
obj -> q[obj -> r ++] = x;
}
int myStackPop(MyStack* obj) {
for (int i = 0; i < obj -> r - obj -> l - 1; i ++) {
myStackPush(obj, obj -> q[obj -> l ++]);
}
return obj -> q[obj -> l++];
}
int myStackTop(MyStack* obj) {
int ans = myStackPop(obj);
myStackPush(obj, ans);
return ans;
}
bool myStackEmpty(MyStack* obj) {
return obj -> l == obj -> r;
}
void myStackFree(MyStack* obj) {
obj -> l = obj -> r = 0;
}
/**
* Your MyStack struct will be instantiated and called as such:
* MyStack* obj = myStackCreate();
* myStackPush(obj, x);
* int param_2 = myStackPop(obj);
* int param_3 = myStackTop(obj);
* bool param_4 = myStackEmpty(obj);
* myStackFree(obj);
*/
标签:obj,int,题解,return,2024,myStackPush,ans,MyStack From: https://www.cnblogs.com/lwj1239/p/18050663