Java与算法(1)
题目: 设计一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
要求:
1 pop,push,getMin操作的时间复杂度都是O(1) 2 设计的栈类型可以使用现成的栈结构
public class Stack_getMIn {
Stack<Integer> stack_data ;
Stack<Integer> stack_min ;
public Stack_getMIn(Stack<Integer> stack_data,Stack<Integer> stack_min) {
this.stack_data = stack_data;
this.stack_min = stack_min;
}
public void push(int newNum) {
if (stack_min.isEmpty()) {
stack_min.push(newNum);
} else if (stack_min.peek()>newNum) {
stack_min.push(newNum);
}
stack_data.push(newNum);
}
public int pop() {
int value = stack_data.peek();
if (stack_min.peek()==value) {
stack_min.pop();
}
return value;
}
public int getMin() {
return stack_min.peek();
}
public static void main(String[] args) {
Stack<Integer> data = new Stack<>();
Stack<Integer> min = new Stack<>();
Stack_getMIn stack_getMIn = new Stack_getMIn(data,min);
stack_getMIn.push(5);
stack_getMIn.push(20);
stack_getMIn.push(0);
System.out.println(stack_getMIn.getMin());
stack_getMIn.pop();
System.out.println(stack_getMIn.getMin());
}
}
题目:
编写一个类,使用两个栈实现队列,支持队列的基本操作(add,poll,peek)
public class StackToQueue {
Stack<Integer> s1 ;
Stack<Integer> s2;
public StackToQueue(Stack<Integer> s1,Stack<Integer> s2) {
this.s1 = s1;
this.s2 = s2;
}
public void add(int num) {
s1.add(num);
}
public int peek() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}
public int pool() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.pop();
}
public static void main(String[] args) {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
StackToQueue stackToQueue = new StackToQueue(s1, s2);
stackToQueue.add(5);
stackToQueue.add(4);
stackToQueue.add(3);
System.out.println(stackToQueue.peek());
}
}