剑指offer——用两个栈来实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
}
public int pop() {
}
}
队列的特点:先入先出
栈的特点:先入后出
自己很笨的方法:在push时,就将stack中的元素进行重新整理,将stack中的元素顺序反过来,然后pop时,就直接出
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if(!stack1.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
stack1.push(node);
while(!stack2.empty()){
stack1.push(stack2.pop());
}
}else if(!stack2.empty()){
while(!stack2.empty()){
stack1.push(stack2.pop());
}
stack2.push(node);
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}else{
stack1.push(node);
}
}
public int pop() {
int res = 0;
if(!stack1.empty()){
res = stack1.pop();
}else if(!stack2.empty()){
res = stack2.pop();
}
return res;
}
}
注:stack1和stack2哪个作为入栈那个作为出栈自己定
别人的方法:
用stack1来做入队列,不改变顺序,后入的放在上面
当出队列时,若stack2为空,则把stack1中的全部出栈到stack2中,此时,顺序就反过来了,然后出栈,
若stack2不为空,则直接出栈,此时stack1中的元素应该在stack2中最下面的元素的后面
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()){
System.out.println("stack is empty");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}

浙公网安备 33010602011771号