首先我们需要明确,在数据结构中,栈是一个先进后出的结构,而队列是先进先出,其次,我们首先要写好关于栈的实现(之前的博客中有写到),话不多说,直接开始实现(依赖于leetcode上的题)
接下来,我将通过简单的图解来说明这次的思路:
好了好了,下面是代码:
//定义栈的结构
typedef int STDataType;
typedef struct Stack
{
STDataType* arr;
int capacity; //栈的空间大小
int top; //栈顶
}ST;
//栈的初始化
void STInit(ST* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
//判断栈是否为空
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
//入栈
void StackPush(ST* ps, STDataType x)
{
assert(ps);
//判断空间是否充足,不足增容
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
STDataType* tmp = (STDataType*)realloc(ps->arr, newcapacity * sizeof(STDataType));
if (tmp==NULL)
{
perror("realloc fail!");
exit(1);
}
ps->arr = tmp;
ps->capacity = newcapacity;
}
//空间足够
ps->arr[ps->top++] = x;
}
//出栈
void StackPop(ST* ps)
{
assert(ps);
//判断栈是否没有数据,是空栈
//assert(ps->arr)
assert(!StackEmpty(ps));
--ps->top;
}
//取栈顶元素
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->arr[ps->top - 1];
}
//获取栈中有效元素个数
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
//栈的销毁
void STDestroy(ST* ps)
{
assert(ps);
if (ps->arr)
{
free(ps->arr);
}
ps->arr = NULL;
ps->top = ps->capacity = 0;
}
/
typedef struct {
ST pushST;
ST PopST;
} MyQueue;
//初始化
MyQueue* myQueueCreate() {
MyQueue* pst=(MyQueue*)malloc(sizeof(MyQueue));
STInit(&pst->pushST);
STInit(&pst->PopST);
return pst;
}
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->pushST,x);
}
int myQueuePop(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{//为空
//导数据
while(!StackEmpty(&obj->pushST))
{
StackPush(&obj->PopST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
//取栈顶,删除栈顶元素并返回栈顶数据
int top=StackTop(&obj->PopST);
StackPop(&obj->PopST);
return top;
}
//取队头
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{//为空
//导数据
while(!StackEmpty(&obj->pushST))
{
StackPush(&obj->PopST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
//取栈顶,删除栈顶元素并返回栈顶数据
return StackTop(&obj->PopST);
}
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->pushST) && StackEmpty(&obj->PopST);
}
void myQueueFree(MyQueue* obj) {
STDestroy(&obj->PopST);
STDestroy(&obj->pushST);
free(obj);
obj=NULL;
}
总结:用栈实现队列比较简单,之后会写用队列实现栈,用队列实现栈较为复杂,在此之前,可以先搞懂本篇博客~~~