面試算法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());
		}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章