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. jQuery学习实用记录

    //jQuery加载 $(document).ready(function(){ //开始编写函数 }); //点击后 上下滑动隐藏效果 $("#id").click(functi ...

  2. windows server 2008 - 创建域和本机用户

    /* * ===================================================================================== * Filenam ...

  3. JS初级-作用域

    作用域:域:空间.范围.区域--作用:读.写    script        全局变量.全局函数        自上而下        函数        由里到外        {}    浏览器 ...

  4. Linux更改服务器Hostname

    在我们需要维护较多的服务器时,有意义的Hostname将时刻提醒我们这台服务器的功能. ****** 1.Debian echo '127.0.1.1 git-server' >> /et ...

  5. WordPaster.exe安装教程

      安装教程: Firefox控件安装教程 Chrome控件安装教程 Chrome 45+控件安装教程 相关问题: 提示Runtime Error错误 360拦截 Chrome启用npapi Fire ...

  6. OpenGL(四)——有用的函数

    概述 1. reshape 定义窗口和图像的映射关系,使在不以纵横比4:3调整窗口大小时,图像不会失真 函数 1. ReShape 如果变更后的窗体的横纵比大于4/3,需要以高为基数,宽为高*4/3, ...

  7. hdu - 3959 Board Game Dice(数学)

    这道题比赛中没做出来,赛后搞了好久才出来的,严重暴露的我薄弱的数学功底, 这道题要推公式的,,,有类似于1*a+2*a^2+3*a^3+...+n*a^n的数列求和. 最后画了一张纸才把最后的结果推出 ...

  8. curl 命令

    看了篇文章: http://www.thegeekstuff.com/2012/04/curl-examples/ 如下: curl支持的协议有:DICT, FILE, FTP, FTPS, Goph ...

  9. AndroidStudio Lod.d在LogCat中不输出

    今天Log.d无论怎样都没有输出. 要在手机开发者选项那开启权限,莫名其妙,之前一直都没事的,具体操作参考:http://jingyan.baidu.com/article/84b4f56597e7b ...

  10. 随机数是骗人的,.Net、Java、C为我作证

    几乎所有编程语言中都提供了"生成一个随机数"的方法,也就是调用这个方法会生成一个数,我们事先也不知道它生成什么数.比如在.Net中编写下面的代码: Random rand = ne ...