剑指offer第20题(包含min函数的栈)

来源:互联网 发布:淘宝店铺鞋子logo 编辑:程序博客网 时间:2024/06/05 04:20

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

java代码:

import java.util.Stack;import java.util.Iterator;public class Solution {    Stack<Integer> stack1=new Stack<Integer>();    public void push(int node) {        stack1.push(node);    }    public void pop() {        stack1.pop();    }    public int top() {        return stack1.peek();    }    public int min() {        int min=stack1.peek();        int temp;        Iterator<Integer> it=stack1.iterator();        while(it.hasNext()){            temp=it.next();            if(min>temp){                min=temp;            }        }        return min;    }}
python代码;

# -*- coding:utf-8 -*-class Solution:    stack=[]    def push(self, node):        self.stack.append(node)    def pop(self):        self.stack.pop()    def top(self):        return self.stack[0]    def min(self):        return min(self.stack)