剑指offer(20)包含min函数的栈
生活随笔
收集整理的這篇文章主要介紹了
剑指offer(20)包含min函数的栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?
import java.util.Stack;public class Solution {//創建倆個輔助棧,stack1用來存放壓入的元素,stack2用來保存較小元素Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();//public void push(int node) {//把節點直接壓入stack1;stack1.push(node);//如果stack2為空,或者node小于stack2的頂端元素if(stack2.isEmpty()||node<stack2.peek()){//把node值壓入stack2stack2.push(node);}else{//否則,將stack2的頂端元素重復存一下;保證stack2的頂端元素不增stack2.push(stack2.peek());}}//出棧public void pop() {stack2.pop();}//取頂棧的元素public int top() {return stack1.peek();}//stack2的頂端元素就是最小的public int min() {return stack2.peek();} }參考:http://www.cnblogs.com/edisonchou/p/4777459.html?
總結
以上是生活随笔為你收集整理的剑指offer(20)包含min函数的栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer(21)栈的压入、探出序列
- 下一篇: 剑指offer(23)二叉搜索树的后序遍