剑指offer(十七)之包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

代码1:

<span style="font-family:SimSun;font-size:18px;">import java.util.Stack;

public class Solution {
    
    Stack stack1=new Stack();
    Stack stack2=new Stack();

    
    public void push(int node) {
        
        stack1.push(node);
        //stack2.push(node);
        
    }
    
    public void pop() {
        if(!(stack1.empty()))
       		 stack1.pop(); 
             //stack2.pop(); 
    }
    
    public int top() {
      if(!stack1.empty())
          return (int)stack1.peek();
      else 
          return 0;
    }
    
    public int min() {        
        if(stack1.empty()){
            return 0;
        }
        //if(stack2.empty()){
           // return 0;
        //}
        //stack2=stack1;
        int min=(int)stack1.peek();               
        while(!stack1.isEmpty()){  
                if(min>=(int)stack1.peek()){
                min=(int)stack1.peek();
                
             }
            stack2.push(stack1.peek());
            stack1.pop();
        }
        while(!stack2.isEmpty()){
            stack1.push(stack2.peek());
            stack2.pop();
        }
        return min;        
    }
}</span>
代码2:

<span style="font-size:18px;">import java.util.Stack;
 
public class Solution {
 
    Stack s1=new Stack();
    Stack min=new Stack();
    public void push(int node) {
        if(min.empty()){
            min.push(node);
        }else{
            int top=(int)min.peek();
            if(node<top){
               min.push(node);
            }else{
                min.push(top);
            }
        }
        s1.push(node);
    }
     
    public void pop() {
        if(!(s1.empty())){
            s1.pop();
            min.pop();
        }
    }
     
    public int top() {
        return (int)s1.peek();
    }
     
    public int min() {
       if(min.empty()){
           return 0;
       }
       return (int)min.peek();    
    }</span>


你可能感兴趣的:(剑指offer(十七)之包含min函数的栈)