数据结构与算法之栈与队列

package StackAndQueueSummary;

import java.util.Stack;

/*
 * 设计一个栈,实现min,push。pop
 * 上一个方法是使用一个辅助栈来存储最小元素,
 * 现在这个方法使用一个栈,一个栈当两个栈使用,
 * 就是说:每次push操作的时候,先入栈当前要被栈的元素,在入栈当前栈中最小的元素;
 * 同理,pop操作也是每次弹出两个元素,首先弹出最小值,再弹出要被移除的元素
 */
public class NewStack2 {
	private Stack<Integer> stack;
	public NewStack2(){
		stack = new Stack<>();
	}
	public void push(int item){
		if(stack.isEmpty()){
			stack.push(item);//先入栈要被存储的元素
			stack.push(item);//再入栈当前栈中的最小值
		}else{
			if( item < stack.peek()){
				//说明当前栈中元素都小于item,所以最小值为item
				stack.push(item);
				stack.push(item);//存入当前序列中的最小值
			}else{
				//说明当前栈中存在小于item的元素,所以最小值仍然为原来的最小值
				int min = stack.peek();
				stack.push(item);
				stack.push(min);
			}
		}
	}
	public int peek() throws Exception{
		if(stack.isEmpty()){
			throw new Exception("The stack is empty");
		}
		/*
		int min = stack.pop();//先把最小元素弹出
		int res  =stack.pop();//再将要返回的元素弹出,并保存该值
		stack.push(res);//再将刚才弹出的元素入栈
		stack.push(min);//再将刚才弹出的元素入栈
		*/
		//该方法的实现也可以调用本类自己实现的pop和push方法
		int res = this.pop();
		this.push(res);
		return res;
	}
	
	public int pop() throws Exception{
		if(stack.isEmpty()){
			throw new Exception("The stack is empty");
		}
		stack.pop();//先把最小元素弹出
		return stack.pop();//再将要返回的元素弹出,并返回该值
	}
	
	public int min() throws Exception{
		if(stack.isEmpty()){
			throw new Exception("The stack is empty");
		}
		return stack.peek();//栈顶元素即为当前栈中元素的最小值
	}
	public static void main(String[] args) throws Exception {
		NewStack2 newStack2 = new NewStack2();
		newStack2.push(11);
		newStack2.push(9);
		newStack2.push(2);
		newStack2.push(8);
		
		System.out.println(newStack2.peek());//8
		System.out.println(newStack2.min());//2
		newStack2.pop();
		System.out.println(newStack2.peek());//2
		newStack2.pop();
		
		System.out.println(newStack2.min());//9
		
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值