顺序栈:
package SeqStack;public class Stack {private int top;private int base[];private int stackSize;public Stack(){stackSize = 100;base = new int[stackSize];top = -1;}public Stack(int n){stackSize = n;base = new int[stackSize];top = -1;}public boolean isFull(){if (top==stackSize-1) return true;return false;}public boolean isEmpty(){if (top==-1) return true;return false;}public boolean pushStack(int e){if (isFull()) return false;base[++top] = e;return true;}public boolean popStack(){if (isEmpty()) return false;--top;return true;}public int topStack(){if (isEmpty()){System.out.println("The Stack is empty");return 0;}return base[top];}}
测试类:
package SeqStack;public class TestStack {public static void main(String[] args){Stack s = new Stack();s.pushStack(23);s.pushStack(12);s.pushStack(45);System.out.println(s.topStack());s.popStack();System.out.println(s.topStack());s.popStack();s.popStack();s.popStack();}
}
链栈:
package LinkStack;public class Stack {private class StackNode{int data;StackNode next;public StackNode(int e){data = e;next = null;}}private StackNode top;public Stack(){top = null;}public boolean isEmpty(){if (top==null) return true;return false;}public boolean pushStack(int e){StackNode s = new StackNode(e);s.next = top;top = s;return true;}public boolean popStack(){if (isEmpty()) return false;StackNode p = top;top = top.next;p.next = null;return true;}public int topStack(){if (isEmpty()){System.out.println("The stack is empty");return 0;}return top.data;}}
测试类:
package LinkStack;import LinkStack.Stack;public class TestStack {public static void main(String[] args){Stack s = new Stack();s.pushStack(23);s.pushStack(12);s.pushStack(45);System.out.println(s.topStack());s.popStack();System.out.println(s.topStack());s.popStack();s.popStack();s.popStack();}
}