Interview questions queue with two stacks 09

A queue is implemented with two stacks. The following statement queue, implement its two functions appendTail and deleteHead, were completed at the end of the queue insert and delete integer integer in the head of the queue function. (If there is no queue element, deleteHead operation returns -1)

Example 1:

Input:
[ "CQueue", "appendTail", "deleteHead", "deleteHead"]
[[], [. 3], [], []]
Output: [null, null, 3, -1]
Example 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:

1 <= values <= 10000
will most appendTail, deleteHead were 10,000 calls

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
 

Solution: the establishment of two stacks, add elements from a tail, a reverse element is completed.
A first additive element directly append
a second stack is divided into three cases
1. If stack2 present elements of stack2 be directly returned pop the top element
2. If stack1 no elements returns -1
3. If the presence of elemental stack1 , then stack1 the elements placed after stack2 in the stack, then pop stack2 element is the first element of the queue

class CQueue(object):

    def __init__(self):
        self.stack1=[]
        self.stack2=[]

    def appendTail(self, value):
        """
        :type value: int
        :rtype: None
        """
        self.stack1.append(value)

    def deleteHead(self):
        """
        :rtype: int
        """
        if self.stack2:
            return self.stack2.pop()
        if not self.stack1:     #不能用 self.stat1 is None判断为空
            return -1
        while self.stack1:
            self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

 

Published 395 original articles · won praise 126 · Views 200,000 +

Guess you like

Origin blog.csdn.net/memory_qianxiao/article/details/104931422