码迷,mamicode.com
首页 > 其他好文 > 详细

包含min函数的栈

时间:2019-07-02 09:30:26      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:形式   net   auto   span   todo   rgs   sub   static   describe   

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
 
我们一直要知道关于Stack的方法。查看JDK1.8,如下所示:
技术图片
 
时间复杂度:
https://www.toutiao.com/i6593144782992704007/ 【转】程序员小灰 (使用漫画的形式,生动,能让人自动的往下看)
 
 1 import java.util.Iterator;
 2 import java.util.Stack;
 3 /*
 4  * 题目描述
 5  * 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
 6  */
 7 
 8 
 9 
10 public class Main20 {
11 
12     Stack<Integer> stack = new Stack<>();
13     
14     public static void main(String[] args) {
15         // TODO Auto-generated method stub
16 
17     }
18     
19     public void push(int node) {
20         stack.push(node);
21     }
22     
23     public void pop() {
24         stack.pop();
25     }
26     
27     public int top() {
28         return stack.peek();
29     }
30     
31     public int min() {
32         int min = stack.peek();
33         int temp;
34         
35         Iterator<Integer> it = stack.iterator();
36         while(it.hasNext()) {
37             temp = it.next();
38             if (temp < min) {
39                 min = temp;
40             }
41         }
42         return min;
43     }

 

包含min函数的栈

标签:形式   net   auto   span   todo   rgs   sub   static   describe   

原文地址:https://www.cnblogs.com/strive-19970713/p/11118396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!