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

栈的压入、弹出序列

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

相关推荐

不愿透露姓名的神秘牛友
07-08 14:08
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司7个岗位
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务