您的位置:首页 > Web前端

剑指offer 栈和队列

2015-09-19 13:19 288 查看


递归

深度优先

队列

分层

广度优先

阻塞队列

优先队列

1.1 题目(面试题7):用两个栈实现队列

解法一:一个栈实现队列offer(),一个栈实现队列的poll();

import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(node);
}

public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
解法二:多线程同步的状态,加锁

1.2 题目(面试题21):包含min函数的栈

解法一:有意思的地方在与添加辅助栈,因为有可能弹出最小值,所以需要用辅助栈更新最小值

import java.util.Stack;

public class Solution {
Stack<Integer> stack=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node) {
if(stack2.isEmpty())
stack2.push(node);
else if(node<stack2.peek())
stack2.push(node);
stack.push(node);
}

public void pop() {
if(stack.peek()==stack2.peek())
stack2.pop();
stack.pop();
}

public int top() {
return stack.peek();
}

public int min() {
return stack2.peek();
}
}
1.3 题目(面试题22):栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
import java.util.Stack;

public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack s=new Stack();
if(pushA.length==0 && popA.length==0) return false;
int len=pushA.length;
for(int i=0,j=0;i<len;i++){
s.push(pushA[i]);
while(!s.isEmpty() && s.peek().equals(popA[j])){
s.pop();
j++;
}
if(j==len){
return true;
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: