一、队列模拟实现栈
1、题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(
push
、top
、pop
和empty
)。
2、过程分析
3、代码实现
class MyStack {
public:
MyStack() {
}
queue<int> q1;
queue<int> q2;
void push(int x) {
if(q1.empty())
{
q2.push(x);
}
else
{
q1.push(x);
}
}
int pop() {
if(q1.empty())
{
while(q2.size()>1)
{
q1.push(q2.front());
q2.pop();
}
int x=q2.front();
q2.pop();
return x;
}
else
{
while(q1.size()>1)
{
q2.push(q1.front());
q1.pop();
}
int x=q1.front();
q1.pop();
return x;
}
}
int top() {
if(q1.empty())
{
return q2.back();
}
else
{
return q1.back();
}
}
bool empty() {
return q1.empty()&&q2.empty();
}
};
二、栈模拟实现栈
1、题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(
push
、pop
、peek
、empty
):
2、过程分析
3、代码实现
typedef int StackDataType;
typedef struct Stack
{
StackDataType* s;
int top;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackDestroy(Stack* ps);
bool StackEmpty(Stack* ps);
void StackPush(Stack* ps, StackDataType x);
void StackPop(Stack* ps);
StackDataType StackTop(Stack* ps);
int StackSize(Stack* ps);
void StackInit(Stack* ps)
{
assert(ps);
ps->capacity=ps->top=0;
ps->s=NULL;
}
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->s);
ps->s=NULL;
ps->capacity=ps->top=0;
}
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->top==0;
}
void StackPush(Stack* ps, StackDataType x)
{
assert(ps);
if(ps->capacity==ps->top)
{
int newcapacity=ps->capacity==0?4:ps->capacity*2;
StackDataType* tmp=(StackDataType*)realloc(ps->s,newcapacity*sizeof(StackDataType));
if(tmp==NULL)
{
perror("realloc failed!");
exit(-1);
}
ps->s=tmp;
}
ps->s[ps->top]=x;
ps->top++;
}
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->top);
ps->top--;
}
StackDataType StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->s[ps->top-1];
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
typedef struct {
Stack* pushst;
Stack* popst;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* q=(MyQueue*)malloc(sizeof(MyQueue));
q->pushst=(Stack*)malloc(sizeof(Stack));
q->popst=(Stack*)malloc(sizeof(Stack));
StackInit(q->pushst);
StackInit(q->popst);
return q;
}
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 x=StackTop(obj->popst);
StackPop(obj->popst);
return x;
}
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(obj->popst))
{
while(!StackEmpty(obj->pushst))
{
StackPush(obj->popst,StackTop(obj->pushst));
StackPop(obj->pushst);
}
}
int x=StackTop(obj->popst);
return x;
}
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(obj->pushst)&&StackEmpty(obj->popst);
}
void myQueueFree(MyQueue* obj) {
free(obj->popst);
free(obj->pushst);
obj->popst=obj->pushst=NULL;
free(obj);
}