21.定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路:定义两个栈,一个存放入的值。另一个存最小值。
代码实现:
public void push(int node) {
stack1.push(node);
if (stack2.isEmpty()) {
stack2.push(node);
}else {
if (stack2.peek() > node) {
stack2.push(node);
}
}
}
public void pop() {
if (stack1.pop() == stack2.peek()) {
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
22.输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:用栈来压入弹出元素,相等则出栈。
代码实现:
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (pushA == null || popA == null) {
return false;
}
Stack<Integer> stack = new Stack<>();
int index = 0;
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.isEmpty() && stack.peek() == popA[index]) {
stack.pop();
index++;
}
}
return stack.isEmpty();
}
23.从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:利用队列(链表)辅助实现。
代码实现:
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
list