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. 【java】:定时任务

    PS:转 http://blog.csdn.net/lotusyangjun/article/details/6450421/

  2. 表A的数据减去表B ,最终得到表C

    ==========表A数据如下:                 表B数据如下:cr     zc     lx                     cr    zc    lx100   10 ...

  3. centos(Linux)系统阿里云ECS搭建 jdk,tomcat和MySQL环境,并部署web程序

    之前我对这个东西一无所知,攻击力为0,谢谢各个论坛上面的兄弟们的帮助. 过程: 首先ssh远程登陆: ssh root@你的公网ip ,输入密码 1,jdk我用的版本是jdk-7u80-linux-x ...

  4. 【kd-tree】bzoj1941 [Sdoi2010]Hide and Seek

    枚举每个点,计算离他最近的和最远的点. #include<cstdio> #include<cmath> #include<algorithm> using nam ...

  5. nginx实现访问网站或目录密码认证保护

    添加目录登陆认证 location / { auth_basic "提示"; auth_basic_user_file /usr/conf/htpasswd; } auth_bas ...

  6. 做梦想起来的C#简单实现贪吃蛇程序(LinQ + Entity)

    最近一直在忙着单位核心开发组件的版本更新,前天加了一个通宵,昨天晚上却睡不着,脑子里面突然不知怎的一直在想贪吃蛇的实现方法.以往也有类似的情况,白天一直想不通的问题,晚上做梦有时会想到更好的版本,于是 ...

  7. 跟我一起学WCF(4)——第一个WCF程序

    一.引言 前面几篇文章分享了.NET 平台下其他几种分布式技术,然而前面几种分布式技术专注于某一特定的领域,并且具有不同编程接口,这使得开发人员需要掌握多个API的使用.基于这样的原因,微软在.NET ...

  8. [UML]UML系列——协作图(通信图)collaboration diagram

    系列文章 [UML]UML系列——用例图Use Case [UML]UML系列——用例图中的各种关系(include.extend) [UML]UML系列——类图Class [UML]UML系列——类 ...

  9. 你不得不知道的HTML5的新型标签

    <article>标签定义外部的内容.比如来自一个外部的新闻提供者的一篇新的文章,或者来自 blog 的文本,或者是来自论坛的文本.亦或是来自其他外部源内容. <aside>标 ...

  10. ajaxFileUpload上传文件后提示下载的问题

    在某些版本浏览器下ajaxFileUpload上传文件会提示下载, 1:为什么? 可以观察到,即便返回 JsonResult 在返回的头中也没有任何消息体,直接理解为文本了. 2:解决方案 前端: f ...