232. 用栈实现队列

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值