---
title: "stack with min operation"
author: "standalone"
date: "2012-11-06T23:37:05Z"
tags: []
categories: ["编程语言"]
slug: "stack-with-min-operation"
draft: false
lastmod: "2012-11-06T23:41:12Z"
id: 1717855
url: "https://standalone.iteye.com/blog/1717855"
---

How would you design a stack which, in addition to push and pop, also has a function
min which returns the minimum element? Push, pop and min should all operate in
O(1) time.


```java


public class StackWithMin extends Stack<NodeWithMin> {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value, newMin));
}
}
public int min() {
	
if (this.isEmpty()) {
		
return Integer.MAX_VALUE;
	
} else {
		
return peek().min;
	
}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int v, int min){
value = v;
this.min = min;
}
}


```