剑指offer--栈的压入、弹出序列
来源:互联网 发布:es大数据实时分析 编辑:程序博客网 时间:2024/06/18 06:12
import java.util.Stack;/** * 栈的压入,弹出序列 题目:输入两个整数序列,第一个序列表示栈的压入顺序 * ,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不等。例如,序列{1,2,3,4,5}是某栈的压栈顺序,序列{4,5,3,2,1}是该栈 * 序列对应的一个弹出序列,但{4,3,5,1,2}就不可能是该压栈序列的弹出序列 * */public class 面试题31 { public static void main(String[] args) { int[] push1 = { 1, 2, 3, 4, 5 }; int[] pop1 = { 4, 5, 3, 2, 1 }; System.out.println(isPopOrder(push1, pop1)); int[] push2 = { 1, 2, 3, 4, 5 }; int[] pop2 = { 4, 3, 5, 1, 2 }; System.out.println(isPopOrder(push2, pop2)); int[] push3 = { 1 }; int[] pop3 = { 1 }; System.out.println(isPopOrder(push3, pop3)); } public static boolean isPopOrder(int push[], int[] pop) { if (pop == null || push == null || pop.length != push.length)//异常输入判断 return false; Stack<Integer> stack = new Stack<Integer>(); int pop_index = 0, push_index = 0; while (pop_index < pop.length) { int head = pop[pop_index]; if (stack.size() == 0 || stack.peek() != head) { //如果此时栈为空或者栈顶不是出栈序列的头节点 while (push[push_index] != head) { //在入栈序列中搜索头节点 stack.push(push[push_index]); //入栈序列中的元素入栈 push_index++; if (push_index >= push.length) return false; } if (push_index < push.length - 1) push_index++; //找到出栈的头结点,此时的入栈节点位置++ } else if (stack.peek() == head) { //如果此时的栈顶等于头结点 stack.pop(); //栈顶出栈 } System.out.println(head); pop_index++;//找下一个出栈节点 } return true; }}
阅读全文
0 0
- offer,栈的压入、弹出序列
- 【剑指offer】栈的压入弹出序列
- 剑指offer系列源码-栈的压入、弹出序列
- 剑指offer--栈的压入、弹出序列
- 剑指Offer之 - 栈的压入、弹出序列
- 剑指offer:栈的压入、弹出序列
- 《剑指offer》栈的压入、弹出序列
- 剑指Offer系列---(24)栈的压入、弹出序列
- 栈的压入、弹出序列(剑指offer)
- 剑指 offer:栈的压入、弹出序列
- 【剑指Offer】栈的压入、弹出序列
- 剑指offer—栈的压入、弹出序列
- 剑指offer:栈的压入弹出序列
- 剑指Offer-22-栈的压入、弹出序列
- 《剑指offer》——栈的压入、弹出序列
- 剑指offer:栈的压入、弹出序列
- 【剑指offer】之栈的压入弹出序列
- 剑指Offer:栈的压入、弹出序列(JAVA)
- 日期转换类
- 光环国际PMP:项目经理时间管理
- HTML基础(2)
- Machine Learning学习路线
- Darwin框架分析与场景应用
- 剑指offer--栈的压入、弹出序列
- 原生js实现半透明遮罩层
- 代码精简之Lombok
- Maven的pom.xml配置文件详解
- 20170908在线编程之圆周上问两点间的距离问题
- Filter
- 验证码,验证登录/注册,直接附代码
- BAT面试的理论题目
- C# 委托(delegate)事件(event)分析