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

栈的压入、弹出序列

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;
    }
    
}
全部评论

相关推荐

ArisRobert:统一解释一下,第4点的意思是,公司按需通知员工,没被通知到的员工是没法去上班的,所以只要没被通知到,就自动离职。就是一种比较抽象的裁员。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-21 17:16
科大讯飞 算法工程师 28.0k*14.0, 百分之三十是绩效,惯例只发0.9
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务