class MyQueue
{
private:
stack<int> s1;
stack<int> s2;
int front;
public:
MyQueue() {}
void push(int x)
{
if (s1.empty() == true)
{
front = x;
}
s1.push(x);
}
int pop()
{
if (s2.empty() == true)
{
while (s1.empty() == false)
{
s2.push(s1.top());
s1.pop();
}
}
int temp = s2.top();
s2.pop();
return temp;
}
int peek()
{
if (s2.empty() == false)
{
return s2.top();
}
else
{
return front;
}
}
bool empty()
{
return s1.empty() && s2.empty();
}
};
//栈
typedef struct stack_type* Stack;
struct node
{
int val;
struct node* next;
};
struct stack_type
{
struct node* first;
};
//Myqueue
typedef struct {
struct stack_type* s1;
struct stack_type* s2;
} MyQueue;
//栈的操作
bool is_empty(Stack s)
{
if (s->first == NULL)
{
return true;
}
else
{
return false;
}
}
Stack create(void)
{
Stack s = malloc(sizeof(struct stack_type));
s->first = NULL;
return s;
}
void push(Stack s, int x)
{
struct node* new_node = malloc(sizeof(struct node));
new_node->val = x;
new_node->next = s->first;
s->first = new_node;
}
int pop(Stack s)
{
int x;
struct node* old_first;
old_first = s->first;
x = old_first->val;
s->first = old_first->next;
free(old_first);
return x;
}
//myQueue的操作
MyQueue* myQueueCreate(void)
{
MyQueue* myQueue = malloc(sizeof(MyQueue));
myQueue->s1 = create();
myQueue->s2 = create();
return myQueue;
}
void myQueuePush(MyQueue* obj, int x)
{
if (is_empty(obj->s1) == true)
{
push(obj->s1, x);
return;
}
else
{
while (is_empty(obj->s1) == false)
{
push(obj->s2, pop(obj->s1));
}
push(obj->s1, x);
while (is_empty(obj->s2) == false)
{
push(obj->s1, pop(obj->s2));
}
}
}
int myQueuePop(MyQueue* obj)
{
return pop(obj->s1);
}
int myQueuePeek(MyQueue* obj)
{
return obj->s1->first->val;
}
bool myQueueEmpty(MyQueue* obj)
{
return is_empty(obj->s1);
}
void myQueueFree(MyQueue* obj)
{
while (is_empty(obj->s1) == false)
{
pop(obj->s1);
}
free(obj->s1);
free(obj->s2);
free(obj);
}