Leetcode-- 用两个栈实现队列

题目链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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]

 

思路

用两个栈来分别实现删头和加尾的操作;

删头时,如果两个栈都为空,说明队列中没有数;如果尾部栈不为空,将尾部栈转入头部栈中,pop掉第一个;

加尾时,如果头部栈不为空 ,将头部栈转入尾部栈,在最后加入新的value

class CQueue {
    stack head;
    stack tail;
public:
    CQueue() {

    }
    
    void appendTail(int value) {
        while(!head.empty()){
            tail.push(head.top());
            head.pop();
        }
        tail.push(value);
    }
    
    int deleteHead() {
        if(tail.empty()&&head.empty())
            return -1;
        while(!tail.empty()){
            head.push(tail.top());
            tail.pop();
        }
        
        int temp= head.top();
        head.pop();
        return temp;
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */

 

你可能感兴趣的:(leetcode)