面试算法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());
		}
}
GNG
发布了118 篇原创文章 · 获赞 389 · 访问量 68万+

猜你喜欢

转载自blog.csdn.net/so_geili/article/details/100619775