栈与队列的面试题

1.括号匹配问题。

解题思路:1.碰到")“开始弹出栈顶的”(",如果此时栈为空,则返回false。
2.碰到其他内容直接返回false 。
3.字符串结尾时,栈非空返回false。

import java.util.Stack;
public class Parenthesis {
public boolean chkParenthesis(String A, int n) {
Stack<Character> lefts = new Stack<Character>();
if(A == null || A.length() != n){
return false;
}
for(int i = 0; i < n; i++){
if(A.charAt(i) == '('){
lefts.push(A.charAt(i));
}else if(A.charAt(i) == ')'){
if(lefts.empty()){
return false;
}else{
lefts.pop();
}
}else{
return false;
}
}
if(!lefts.empty()){
return false;
}else{
return true;
}
}
}

2.用栈实现队列。

解题思路:栈1用来作入队列;栈2用来出队列,当栈2为空时,栈1全部出栈到栈2,栈2再出栈(即出队列)。

import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}

猜你喜欢

转载自blog.csdn.net/qq_44149554/article/details/90695859