LeetCode:232.用栈实现队列
//两个栈,负负得正→先进先出
//题目都是合法操作,不用判断操作是否合法(如对空栈进行弹栈)
typedef struct {
int stack_in[100];
int stack_out[100];
int stack_in_top;
int stack_out_top;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* p = (MyQueue*)malloc(sizeof(MyQueue));
p->stack_in_top = 0;//莫忘初始化top
p->stack_out_top = 0;
return p;
}
void myQueuePush(MyQueue* obj, int x) {
obj->stack_in[(obj->stack_in_top)++] = x;
}
int myQueuePop(MyQueue* obj) {
//出栈有元素→直接出队;出栈为空→先把入栈元素全部放到出栈再出队
if (obj->stack_out_top == 0) {
while (obj->stack_in_top != 0)
obj->stack_out[(obj->stack_out_top)++] =//入栈后++
obj->stack_in[--(obj->stack_in_top)];//弹栈先--
}
obj->stack_out_top -= 1;//逻辑出栈
return obj->stack_out[obj->stack_out_top];
}
int myQueuePeek(MyQueue* obj) {
int x = myQueuePop(obj);//复用pop函数,类似功能优先进行复用
obj->stack_out_top += 1;//恢复栈帧
return x;
}
bool myQueueEmpty(MyQueue* obj) {
return obj->stack_in_top == 0 && obj->stack_out_top == 0;
}
void myQueueFree(MyQueue* obj) {
obj->stack_in_top = 0;
obj->stack_out_top = 0;
}
/**
* 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);
*/
225. 用队列实现栈
//链表头插法实现
typedef struct list_node{
int val;
struct list_node *next;//命名还未完成,要加struct
}list_node;
typedef struct {
list_node* top;//栈顶
} MyStack;
MyStack* myStackCreate() {
MyStack *obj=(MyStack*)calloc(1,sizeof(MyStack));
return obj;
}
void myStackPush(MyStack* obj, int x) {
list_node* p=(list_node*)calloc(1,sizeof(list_node));
p->val=x;
p->next=obj->top;//头插法
obj->top=p;
}
int myStackPop(MyStack* obj) {
list_node* temp=obj->top;
obj->top=obj->top->next;
int x=temp->val;
free(temp);
return x;
}
int myStackTop(MyStack* obj) {
return obj->top->val;
}
bool myStackEmpty(MyStack* obj) {
return obj->top==NULL;
}
void myStackFree(MyStack* obj) {
if(obj->top==NULL) return;
list_node* p=obj->top;
while(obj->top){
obj->top=obj->top->next;
free(p);//要free p不能直接free top 不然会出现double free 问题
p=obj->top;
}
}
/**
* 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);
*/