题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
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;
}
}