LeedCode刷题笔记-用两个栈实现一个队列
题目描述
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
[“CQueue”,“deleteHead”,“appendTail”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解题代码
typedef struct
{
int len1;//表示第一个栈的长度
int len2;//表示第二个栈的长度
int * stack1;
int * stack2;
} CQueue;
CQueue* cQueueCreate()
{
CQueue * que = (CQueue *)malloc(sizeof(CQueue));
if(que == NULL)
{
return NULL;
}
que->len1 = 0;
que->len2 = 0;
que->stack1 = (int *)malloc(sizeof(int) * 10000);
que->stack2 = (int *)malloc(sizeof(int) * 10000);
return que;
}
void cQueueAppendTail(CQueue* obj, int value)
{
if(obj == NULL)
{
return;
}
if(obj->len1 > 10000)
{
return;
}
obj->stack1[obj->len1++] = value;
return;
}
int cQueueDeleteHead(CQueue* obj)
{
if(obj == NULL)
{
return -1;
}
int data = -1;
//这是使用的是第二个栈来接收第一个栈的倒置栈,这样,第二栈出栈,就类似于队列的出列了
if(obj->len2 > 0)
{
data = obj->stack2[obj->len2 -1];
obj->len2--;
return data;
}
if(obj->len2 == 0 && obj->len1 > 0)
{
while(obj->len1 > 0)
{
//这里之所以这么操作,是因为栈顶的表示为len - 1,栈底还是从0开始的呀,所以是len2++;--len1
obj->stack2[obj->len2++] = obj->stack1[--obj->len1];
}
data = obj->stack2[obj->len2 - 1];
obj->len2--;
}
return data;
}
void cQueueFree(CQueue* obj)
{
if(obj == NULL)
{
return;
}
if(obj->stack1 != NULL)
{
free(obj->stack1);
obj->stack1 = NULL;
}
if(obj->stack2 != NULL)
{
free(obj->stack2);
obj->stack2 = NULL;
}
free(obj);
obj = NULL;
}
/**
* Your CQueue struct will be instantiated and called as such:
* CQueue* obj = cQueueCreate();
* cQueueAppendTail(obj, value);
* int param_2 = cQueueDeleteHead(obj);
* cQueueFree(obj);
*/
解题总结
- 抓住主要实现方法,就是一个栈做另外一个栈的倒置栈,这样出栈就类似于队列的出队了
- 还有就是编程的细节了,包括什么标点符号,以及len–,还是–len,自己一定要想清楚了