1. 栈的基本使用
import java.util.Stack; //引用栈
//初始化
Stack<Integer> stack = new Stack<Integer>();
//进栈
stack.push(Element);
//出栈
stack.pop();
//取栈顶值(不出栈)
stack.peek();
//判断栈是否为空
stack.isEmpty()
2.实例
来源:剑指offer
(1)用两个栈实现队列
用两个栈来实现一个队列,完成队列的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) {
stack1.push(node);
}
public int pop() {
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
(2)包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
import java.util.Stack;
public class Solution {
Stack<Integer> stack =new Stack<Integer>();
Stack<Integer> minstack= new Stack<Integer>();
public void push(int node) {
stack.push(node);
if (!minstack.isEmpty()){
if (minstack.peek()>node){ //若minstack栈顶值>node,node进栈;否则,再push一次栈顶值
minstack.push(node);
}
else{
minstack.push(minstack.peek());
}
}
else{
minstack.push(node);
}
}
public void pop() {
stack.pop();
minstack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minstack.peek();
}
}
(3)栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (pushA == null || pushA.length !=popA.length){
return false;
}
Stack<Integer> stack = new Stack<Integer>();
int index=0;
for (int i=0;i<pushA.length;i++){
stack.push(pushA[i]);
//若栈顶值等于popA[index],stack就出栈,同时stack不为空
//用while循环是因为每pop一次,下一次依然可能是pop不是push,所以要index+1循环判断下一个值
while (!stack.isEmpty() && stack.peek() == popA[index]){
stack.pop();
index +=1;
}
}
if (stack.isEmpty()){
return true;
}
else {
return false;
}
}
}