zoukankan      html  css  js  c++  java
  • 5、用两个栈实现队列

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    =================Python===============

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

    ====================Java=================

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.add(node);
        }
        
        public int pop() throws Exception {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.add(stack1.pop());
                }
            }
            if (stack2.isEmpty())
                throw new Exception("error");
            return stack2.pop();
        }
    }
  • 相关阅读:
    例2-3
    例2-2
    例2-1
    p14
    第一次作业
    例1-1
    第二次作业(2)
    第二次作业
    第三章3-3
    第三章3-2
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13537959.html
Copyright © 2011-2022 走看看