题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

import java.util.ArrayList;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        int j = 0;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < pushA.length; i++) {
            stack.push(pushA[i]);
            while (stack.top() != null && (int) stack.top() == popA[j]) {
                j++;
                stack.pop();
            }
        }
        while (stack.top() != null) {
            if ((int) stack.top() != popA[j]) return false;
            j++;
            stack.pop();
        }
        return true;
    }
}
class Node<T> {
    public T data;
    public Node next;
    
}
class Stack<T> {
    private Node<T> head;
    public Stack() {
        head = new Node<T>();
        head.next = null;
        head.data = null;
    }
    
    public boolean isEmpty() {
        return head.next == null;
    }
    
    public Stack(T data) {
        head = new Node<T>();
        head.next = null;
        head.data = data;
    }
    
    public int size() {
        int size = 0;
        Node<T> cur = head.next;
        while (cur.next != null) {
            size++;
            cur = cur.next;
        }
        return size;
    }
    
    public void push(T e) {
        Node<T> tlNode = new Node<>();
        tlNode.data = e;
        tlNode.next = head.next;
        head.next = tlNode;
    }
    
    public T pop() {
        Node<T> popNode = head.next;
        if (popNode == null) return null;
        head.next = popNode.next;
        return popNode.data;
    }
    
    public T top() {
        Node<T> topNode = head.next;
        if (topNode == null) return null;
        return topNode.data;
    }
    
}
全部评论

相关推荐

10-15 09:13
已编辑
天津大学 soc前端设计
点赞 评论 收藏
分享
11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务