面试算法1---栈和队列


一、设计一个有getMin功能的栈

  1. 实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
  2. pop、push、getMin操作的时间复杂度都是O(1);
  3. 设计的栈类型可以使用现成的栈结构。
import java.util.Stack;

public class MyStack {
	private Stack<Integer> stackData=new Stack<Integer>();
	private Stack<Integer> stackMin=new Stack<Integer>();
	
	public void push(Integer data) {
		stackData.push(data);
		if(stackMin.isEmpty() || data <= stackMin.peek()) {
			stackMin.push(data);
		}
	}
	
	public int pop() {
		if(stackData.isEmpty()) {
			throw new RuntimeException();
		}
		int res = stackData.pop();
		if(res <= stackMin.peek()) {
			stackMin.pop();
		}
		return res;
	}
	
	public int getMin() {
		int res = 0;
		if(stackMin.isEmpty()) {
			throw new RuntimeException("栈为空无法弹出元素");
		}
		res= stackMin.peek();
		return res;
	}
}

二、由两个栈组成的队列

  1. 编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)
class TwoStackQueue{
	private Stack<Integer> stackPush=new Stack<Integer>();
	private Stack<Integer> stackPop=new Stack<Integer>();
	//进队
	public void add(Integer data) {
		this.stackPush.push(data);
	}
	
	//出队
	public Integer poll() {
		if(stackPop.isEmpty() && stackPush.isEmpty()) {
			throw new RuntimeException("没有元素,异常");
		}else if(stackPop.isEmpty()) {
			while(!stackPush.isEmpty()) {
				stackPop.push(stackPush.pop());
			}
		}
		return stackPop.pop();
	}
}

三、用一个栈实现另一个栈的排序

一个栈中元素的类型为整型,现在想将该栈从顶到底从大到小的顺序排序,只允许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。

public void sortStackByStack(Stack<Integer> data) {
		Stack<Integer> help=new Stack<Integer>();
		Integer cur = 0;
		while(!data.isEmpty()) {
			cur=data.pop();
			
			while(!help.isEmpty() && cur > help.peek()) {
				data.push(help.pop());
			}
			help.push(cur);
		}
		while(!help.isEmpty()) {
			data.push(help.pop());
		}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值