Detailed Explanation of Queue with Two Stacks (with Java and Python source code)-"Sword Finger Offer"

1. Title description

Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

2. Analysis

The queue is: " first in first out "
stack is: " first in last out "

How to use two stations to implement a queue, see the two stacks in the following figure: inand out
Picture link https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3ea280b5-be7d-471b-ac76-ff020384357c.gif
Illustration: Push operation directly to the inmiddle, pop operation needs to be classified: if the outstack is empty, then inthe data in the outstack needs to be transferred to the stack, and then When outpopping the stack, if the outstack is not empty, just pop directly.

3. Code implementation

3.1 Java implementation

import java.util.Stack;

public class JzOffer5 {
    
    
    Stack<Integer> in = new Stack<Integer>();
    Stack<Integer> out = new Stack<Integer>();

    public void push(int node){
    
    
        in.push(node);
    }

    public int pop(){
    
    
        if (out.isEmpty()) {
    
    
            while (!in.isEmpty()) {
    
    
                out.push(in.pop());
            }
        }
        return out.pop();
    }
}

3.2 Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    
    def push(self, node):
        # write code here
        self.stack1.append(node)
    def pop(self):
        # return xx
        if len(self.stack2) == 0:
            while len(self.stack1) != 0:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

Guess you like

Origin blog.csdn.net/weixin_44285445/article/details/108134618