面試中玉罐,算法題是無法回避的,問的太深似乎沒必要潘拨,畢竟應(yīng)聘的不是算法崗位厌小,如果問到算法題了,那一般肯定會是常見的战秋,你聽過,但是又不是很熟悉的東西讨韭。我們要做的就是把不熟悉的東西搞熟悉了脂信,不會的東西搞會了,做好充分的準(zhǔn)備透硝。
下面這個(gè)題就比較有意思了狰闪,考的是對數(shù)據(jù)結(jié)構(gòu)的基本理解,看下怎么實(shí)現(xiàn)濒生。兩個(gè)棧如何實(shí)現(xiàn)一個(gè)隊(duì)列埋泵?
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class QueueImplementByTwoStacks {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
QueueImplementByTwoStacks() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public Integer poll() {
Integer it = null;
if (!stack2 .empty()) {
it = stack2.pop();
} else {
while (!stack1 .empty()) {
it = stack1.pop();
stack2.push( it);
}
if (!stack2 .empty()) {
it = stack2.pop();
}
}
return it ;
}
public Integer offer(int o ) {
stack1.push( o);
return o ;
}
public static void main(String[] args) {
QueueImplementByTwoStacks queue = new QueueImplementByTwoStacks();
List<Integer> list = new ArrayList<Integer>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
list.add( queue.poll());
System. out.println(list .toString());
queue.offer(4);
list.add( queue.poll());
System. out.println(list .toString());
queue.offer(5);
System. out.println(list .toString());
list.add( queue.poll());
/*list.add(queue.poll());
list.add(queue.poll());*/
System. out.println(list .toString());
}
}