一、题目描述
二、思路
自定义一个队列,里边用栈(数组)去实现队列。
当要将元素 x 压入栈顶时,直接将元素 x 放入栈顶;
当要移除并返回栈顶元素时,将除了栈顶元素外的元素全部复制到栈顶元素之后,返回此时 bottom 所指元素,并将 bottom 值加一;
当要返回栈顶元素时,直接输出(栈顶指针 - 1 )所指元素;
当需要对队列进行判空时,若bottom == top,则为空;反之不为空。
三、解题过程
-
定义队列
typedef struct {
int queue[100];
int top;
int bottom;
} MyStack;
-
实现初始化队列接口函数
MyStack* myStackCreate() {
MyStack* stack = (MyStack*)malloc(sizeof(MyStack));
stack -> top = 0;
stack -> bottom = 0;
return stack;
}
-
实现push接口函数
- 将元素 x 压入栈顶
void myStackPush(MyStack* obj, int x) {
obj -> queue[(obj -> top)++] = x;
}
-
实现pop接口函数
- 移除并返回栈顶元素
int myStackPop(MyStack* obj) {
int top = obj -> top;
int bottom = obj -> bottom;
int len = top - bottom;
while(len-- > 1){
obj -> queue[top++] = obj -> queue[bottom++];
}
obj -> top = top;
int res = obj -> queue[bottom++];
obj -> bottom = bottom;
return res;
}
-
实现top接口函数
- 返回栈顶元素
int myStackTop(MyStack* obj) {
return obj -> queue[(obj -> top) - 1];
}
-
实现判空接口函数
- 如果栈是空的,返回
true
;否则,返回false
bool myStackEmpty(MyStack* obj) {
return obj -> top == obj -> bottom;
}
-
实现清空队列接口函数
void myStackFree(MyStack* obj) {
obj -> top = 0;
obj -> bottom = 0;
}
四、代码
typedef struct {
int queue[100];
int top;
int bottom;
} MyStack;
MyStack* myStackCreate() {
MyStack* stack = (MyStack*)malloc(sizeof(MyStack));
stack -> top = 0;
stack -> bottom = 0;
return stack;
}
void myStackPush(MyStack* obj, int x) {
obj -> queue[(obj -> top)++] = x;
}
int myStackPop(MyStack* obj) {
int top = obj -> top;
int bottom = obj -> bottom;
int len = top - bottom;
while(len-- > 1){
obj -> queue[top++] = obj -> queue[bottom++];
}
obj -> top = top;
int res = obj -> queue[bottom++];
obj -> bottom = bottom;
return res;
}
int myStackTop(MyStack* obj) {
return obj -> queue[(obj -> top) - 1];
}
bool myStackEmpty(MyStack* obj) {
return obj -> top == obj -> bottom;
}
void myStackFree(MyStack* obj) {
obj -> top = 0;
obj -> bottom = 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);
*/