Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

题目的意思是实现一个栈,能够实现推入,推出,返回顶端元素,获得最小元素的功能

public class MinClass {

	private Stack<Integer> a = new Stack<Integer>() ;
private Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) {
/**
* 判断最小栈,如果栈为空或者压入的栈值小于栈顶元素,将x压入最小栈
*/
if(minStack.isEmpty() || x<minStack.peek()){
minStack.push(x);
}
a.push(x); }
public void pop() {
/**
* 如果不相等,会把minStack中保存的最小值给推出。所以必须保证minStack中推出
* 的值必须和a中的值一样
*/
if(minStack.peek().equals(a.peek())){
minStack.pop();
}
a.pop();
} public int top() {
return a.peek();
} public int getMin() {
return minStack.peek();
} /**
* 测试
*/
public static void main(){
MinClass obj = new MinClass();
obj.push(10);
obj.push(20);
obj.pop();
obj.push(30);
System.out.println(obj.getMin());
}
}

  

拓  展


图片来自于维基

堆栈(英语:stack),也可直接称栈 由于堆栈数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。栈空间有操作系统自动分配,使用完成后有编译器自动释放,通常用来存放函数的参数值、局部变量的值等。

栈使用的是靠近ALU的一级缓存,他们通常是在调用时处于存储空间中,调用完毕后就会立即释放。与“堆(Heap)"不同,堆内存有程序员释放那个,存放于二级缓存中,结构类似于链表,程序员分配时内存变量的值不一定是连续的,因此,堆处理的速度相比与栈来说速度要慢一些!

(截图来自 计算机系统概论)

如图所示,a)有5个连续的存储空间,每个存储单元为1个字节(这也是目前操作系统内存结构的排列方式,类似于一个大的字节数组)。R6代表栈顶寄存器,用来存储栈顶元素的指针。b)当往栈中push一个元素18以后,栈顶元素指针加1,其他地址不变。c)往栈中压入3个元素后的结果,可以看到不断修改栈顶指针的大小。d)弹出2个元素的结果

下面我们用Java代码实现栈,前文已经说明,实现栈的方式可以有数组,也可以有链表来实现(因为这两个数据结构都是线性结构)

Java的SDK中封装好的有一个Stack,他的常用方法有

empty()

Tests if this stack is empty
peek()

Looks at the object at the top of this stack without removing it from the stack.
pop()

Removes the object at the top of this stack and returns that object as the value of this function.
push(E item)

Pushes an item onto the top of this stack.
栈的数组实现:
/**
* 栈的数组实现方式
* @author CYW
*/
public class ArrayStack {
private long[] stackArray;//数组
private int stackSize;//记录存储记录的最大的条数
private int top = -1;//记录栈顶位置 // 记录分配存储空间的大小
public ArrayStack(int s){
stackArray = new long[s];
top = -1;
stackSize = s;
} public long pop(){
return stackArray[top--];
} public void push(int x){
stackArray[++top] = x;
} public long peek(){
return stackArray[top];
} public boolean isEmpty(){
return (stackArray.length == 0);
} // 测试
public static void main(){
ArrayStack obj = new ArrayStack(100);
obj.push(100);
obj.push(20);
obj.push(10);
obj.push(200);
obj.push(1000);
obj.pop();
/**
*
*/
for (int i = 0;i<obj.top;i++){
System.out.println(obj.stackArray[i]);
}
}
}

 需要注意的一点是:我们在输出数组元素的时候不能根据数组的长度来判断,而必须根据站顶的top来判断!

C++代码

struct Node{
struct Node* pPre;
int data;
}; class ListStack{
private:
//定义指向栈顶元素的指针
struct Node *top; public: void push(int data){
//创建新的变量
struct Node *node = new struct Node();
node->data = data;
node->pPre = top;
//重新定义top的指向
top = node;
} int pop(){ //重新定义top的指向
int temp = top->data;
top =top->pPre;
//返回输出结果
return temp;
} int peek(){
return top->data;
}
//判断是否为空
bool isEmpty(){
if(top){
return true;
}else{
return false;
} } }; int _tmain(int argc, _TCHAR* argv[])
{
ListStack stack;
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50); cout<<stack.pop()<<endl;
cout<<stack.peek()<<endl;
cout<<stack.pop()<<endl;
cout<<stack.pop()<<endl;
cout<<stack.pop()<<endl;
cout<<stack.peek()<<endl;
cout<<stack.pop()<<endl; if(stack.isEmpty()){
cout<<"栈中数据为空!"<<endl;
}else{
stack.pop();
}
return 0;
}

 当然,上面代码中有很多不安全的地方,仅仅是学习的目的,http://shmilyaw-hotmail-com.iteye.com/blog/1825171 从Java给出了比较好的解释。

 
 

MinStack的更多相关文章

  1. LintCode MinStack

    Implement a stack with min() function, which will return the smallest number in the stack. It should ...

  2. minStack实现

    设计包含 min 函数的栈(栈)定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素.要求函数 min.push 以及 pop 的时间复杂度都是 O(1). #include <a ...

  3. leetcode算法学习----155. 最小栈(MinStack )

    下面题目是LeetCode算法155题: https://leetcode.com/problems/min-stack/ 题目1:最小函数min()栈 设计一个支持 push,pop,top 操作, ...

  4. [LeetCode] 155. minStack 设计最小栈

    注意:getMin()时间复杂度为O(1) 最原始的方法: class MinStack(object): def __init__(self): """ initial ...

  5. [LeetCode] Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  6. BUG-FREE-For Dream

    一直直到bug-free.不能错任何一点. 思路不清晰:刷两天. 做错了,刷一天. 直到bug-free.高亮,标红. 185,OA(YAMAXUN)--- (1) findFirstDuplicat ...

  7. 二刷Cracking the Coding Interview(CC150第五版)

    第18章---高度难题 1,-------另类加法.实现加法. 另类加法 参与人数:327时间限制:3秒空间限制:32768K 算法知识视频讲解 题目描述 请编写一个函数,将两个数字相加.不得使用+或 ...

  8. (lintcode全部题目解答之)九章算法之算法班题目全解(附容易犯的错误)

    --------------------------------------------------------------- 本文使用方法:所有题目,只需要把标题输入lintcode就能找到.主要是 ...

  9. [ACM训练] 算法初级 之 数据结构 之 栈stack+队列queue (基础+进阶+POJ 1338+2442+1442)

    再次面对像栈和队列这样的相当基础的数据结构的学习,应该从多个方面,多维度去学习. 首先,这两个数据结构都是比较常用的,在标准库中都有对应的结构能够直接使用,所以第一个阶段应该是先学习直接来使用,下一个 ...

随机推荐

  1. Linux下安装软件的一般步骤

    目录 一.解析Linux应用软件安装包 二.了解包里的内容 三.搞定使用tar打包的应用软件 四.搞定使用rpm打包的应用软件 五.搞定使用deb打包的应用程序 一.解析Linux应用软件安装包(回目 ...

  2. Ubuntu10.0.4安装NDK

    android版本遇到.so文件crash,需要使用ndk来定位报错代码. 从这里下载ndk安装文件: http://www.androiddevtools.cn/ 运行 ./android-ndk- ...

  3. 关于卡尔曼滤波(Kalman Filter)的很好讲解

    http://bilgin.esme.org/BitsAndBytes/KalmanFilterforDummies C#代码: double[] Data = new double[] { 0.39 ...

  4. js 格式化日期 ("/Date(1400046388387)/")

    var date = new Date(parseInt(str.replace(/\/Date\((-?\d+)\)\//, '$1'))); var d= date.getFullYear() + ...

  5. java线程详解(三)

    java线程间通信 首先看一段代码 class Res { String name; String sex; } class Input implements Runnable { private R ...

  6. SpringMVC上传文件

    SpringMVC中上传文件还是比较方便的,Spring内置了一些上传文件的支持类,不需要复杂的操作即可上传文件. 文件上传需要两个jar支持,一个是commons-fileupload.jar和co ...

  7. MySQL调优参数

    key_buffer_size 含义:用于索引块的缓冲区大小,增加它可得到更好处理的索引(对所有读和多重写). 影响:对于MyISAM表的影响不是很大,MyISAM会使用系统的缓存来存储数据,所以大量 ...

  8. NSMutableAttributedString/NSAttributedString 富文本设置

    今天在做项目的过程中,我们的设计师想要一种字体四周都带阴影的效果,但是我们平时使用的setShadowColor 和setShadowOffset是达不到这种效果,setShadowOffset 只能 ...

  9. ubuntu apache2 wsgi 部署django

    入题 分为如下几步 1.安装python 2.安装django 3.安装wsgi,如有问题请参照上一篇 ubuntu 编译安装 mod_wsgi 4.与apache集成这里主要讲这部分 环境apach ...

  10. WPF学习开发客户端软件-任务助手(已上传源码)

    本人纯属WPF新手,布局和WPF的开发水平相当欠缺,从个人来说,还是比较喜欢WPF的,有人说WPF是界面加上WINFORM,我不这样认为,WPF与WINFORM主要的不同在于数据绑定.   这个软件虽 ...