目录
链接. - 力扣(LeetCode)
描述
思路
push
pop
peek
empty
代码
链接
. - 力扣(LeetCode)
描述
思路
push
例如我们将10个元素放入栈中,假设最左边为栈顶,最右侧为栈底
则为10,9,8,7,6,5,4,3,2,1
pop
从队列的开头移除并返回元素,队列的开头为最右侧的1
我们先将前面的元素放入空栈中
空栈中元素顺序为2,3,4,5,6,7,8,9,10
我们发现元素顺序反了,说明等下要反转回来
此时原栈中只剩最后一个元素1,我们将1拷贝下来并踢出去即可
此时原栈成为空栈,我们将元素全部放回去即可,原栈顺序改为10,9,8,7,6,5,4,3,2
通过反转我们就顺利的将队列中的第一个元素1给删除了
peek
返回队列开头元素与pop思路基本一致,唯一的不同点为原栈中不需要再将元素1删去,拷贝后直接将元素全部取回来即可。
empty
两个栈均不为空指针即可
代码
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps);
// 入栈
void StackPush(Stack* ps, STDataType data);
// 出栈
void StackPop(Stack* ps);
// 获取栈顶元素
STDataType StackTop(Stack* ps);
// 获取栈中有效元素个数
int StackSize(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps);
// 销毁栈
void StackDestroy(Stack* ps);
void StackInit(Stack* ps) {
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = -1;
}
void StackPush(Stack* ps, STDataType data) {
if (ps->_capacity == ps->_top + 1) {
int newcapacity = ps->_capacity == 0 ? 4 : 2 * ps->_capacity;
STDataType* tmp = (STDataType*)realloc(ps->_a, newcapacity * sizeof(STDataType));
if (tmp == NULL) {
perror("realloc error");
return;
}
ps->_a = tmp;
ps->_capacity = newcapacity;
}
ps->_top++;
ps->_a[ps->_top] = data;
}
void StackPop(Stack* ps) {
if (ps->_top == -1) {
return;
}
ps->_top--;
}
STDataType StackTop(Stack* ps) {
return ps->_a[ps->_top];
}
int StackSize(Stack* ps) {
return ps->_top + 1;
}
int StackEmpty(Stack* ps) {
if (ps->_top == -1)
return 1;
return 0;
}
void StackDestroy(Stack* ps) {
ps->_capacity = 0;
ps->_top = -1;
free(ps->_a);
ps->_a = NULL;
}
typedef struct {
Stack s1;
Stack s2;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* mn = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&(mn->s1));
StackInit(&(mn->s2));
return mn;
}
void myQueuePush(MyQueue* obj, int x) {
Stack* nonempty = &(obj->s1), * empty = &(obj->s2);
if (StackEmpty(nonempty)) {
nonempty = &(obj->s2);
empty = &(obj->s1);
}
StackPush(nonempty, x);
}
int myQueuePop(MyQueue* obj) {
Stack* nonempty = &(obj->s1), * empty = &(obj->s2);
int a;
if (StackEmpty(nonempty)) {
nonempty = &(obj->s2);
empty = &(obj->s1);
}
while (StackSize(nonempty) != 1) {
StackPush(empty, StackTop(nonempty));
StackPop(nonempty);
}
a = StackTop(nonempty);
StackPop(nonempty);
while (StackSize(empty) != 0) {
StackPush(nonempty, StackTop(empty));
StackPop(empty);
}
return a;
}
int myQueuePeek(MyQueue* obj) {
Stack* nonempty = &(obj->s1), * empty = &(obj->s2);
if (StackEmpty(nonempty)) {
nonempty = &(obj->s2);
empty = &(obj->s1);
}
while (StackSize(nonempty) != 1) {
StackPush(empty, StackTop(nonempty));
StackPop(nonempty);
}
int a = StackTop(nonempty);
while (StackSize(empty) != 0) {
StackPush(nonempty, StackTop(empty));
StackPop(empty);
}
return a;
}
bool myQueueEmpty(MyQueue* obj) {
if (StackEmpty(&(obj->s2)) && StackEmpty(&(obj->s1)))
return true;
return false;
}
void myQueueFree(MyQueue* obj) {
StackDestroy(&(obj->s1));
StackDestroy(&(obj->s2));
free(obj);
}