【java】栈(Stack)的基本使用

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;
        }
    }
}
  • 15
    点赞
  • 96
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值