"Sword refers to offer" with two stacks to achieve the queue problem-solving report (Python) __python

Source: Internet
Author: User
"Sword refers to offer" with two stacks to achieve the queue problem-solving report (Python)

tags (space-delimited): Leetcode

Topic Address: Https://www.nowcoder.com/ta/coding-interviews topic Description:

Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int. Ways

The first stack temporarily saves the inserted data, and when the pop-up function is invoked, it pops up directly if the Stack2 is not empty, and the data in the stack1 pops up into the stack2.

This will not conflict, and because Stack2 save the old data, pop-up must conform to the rules of the queue.

#-*-Coding:utf-8-*-
class Solution:
    def __init__ (self):
        self.stack1 = []
        self.stack2 = []

    def Push (self, node):
        self.stack1.append (node)

    def pop (self):
        if Self.stack2: Return
            Self.stack2.pop ()
        else: While
            self.stack1:
                self.stack2.append (Self.stack1.pop ()) return
            Self.stack2.pop ()
Date

March 9, 2018

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.