// 栈:
class Stack<T> {
private LinkedList<T> storage = new LinkedList<T>();
public void push(T v) {storage.addFirst(v);}
public T peek() {return storage.getFirst();}
public T pop() {return storage.removeFirst();}
public boolean empty() {return storage.isEmpty();}
public String toString() {return storage.toString();}
}
//栈的压入和弹出序列
//输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。
//例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
public class StackSeq {
public static void main(String []args) {
int [] a = {1,2,3,4,5};
int [] b = {5,4,3,1,2};
judgeSeq(a,b);
}
public static void judgeSeq(int[] pushSeq,int[] dataSeq){
if(pushSeq==null||dataSeq==null) return;
int pushLength = pushSeq.length;
int dataLength = dataSeq.length;
if(pushLength==0||dataLength==0||pushLength!=dataLength){
return;
}
Stack<Integer> stack = new Stack<Integer>();
int i=0,j=0;
stack.push(pushSeq[i++]);
while(j<dataLength||i<pushLength){
while(stack.empty()||(i<pushLength&&dataSeq[j]!=stack.peek())){
stack.push(pushSeq[i++]);
}
if(dataSeq[j]==stack.peek()){
stack.pop();
j++;
}else {
if(i>=pushLength)
break;
}
}
if(stack.empty()){
System.out.println(true);
}
else System.out.println(false);
}
}
//面试题21:包含min函数的栈
//题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
import java.util.LinkedList;
public class MinInStack2 {
public static void main(String[]args) {
Stacks<Integer> s = new Stacks<Integer>();
s.push(3);
s.push(4);
s.push(2);
s.push(1);
s.pop();
s.pop();
s.push(0);
System.out.println(s.min());
}
}
class Stacks<T> {
private Stack<Integer> stackData = new Stack<Integer>();
private Stack<Integer> stackMin = new Stack<Integer>();
public void push(T v) {
int value = (Integer)v;
stackData.push(value);
if(stackMin.empty()||value<stackMin.peek()) {
stackMin.push(value);
}else {
stackMin.push(stackMin.peek());
}
}
public void pop() {
if(!stackData.empty()&&!stackMin.empty()) {
stackData.pop();
stackMin.pop();
}
}
@SuppressWarnings("unchecked")
public T min() {
if(!stackData.empty()&&!stackMin.empty()) {
return (T)stackMin.peek();
}
return null;
}
}