/** * 单个节点 * * @author Lison-Liou * */ public class Node { int data = 0; Node next;
public Node() { }
public Node(int data) { this.data = data; }
public Node(int data, Node next) { this.data = data; this.next = next; } } /** * 后进先出 LIFO LAST IN FIRST OUT * * @author Lison-Liou * */ public class MyStack {
Node top; int size;
public void initStack() { top = null; }
public boolean isEmpty() { return size == 0; }
public void push(int x) { top = new Node(x, top); size++; }
public int pop() {
Node t = top; top = top.next; size--; return t.data; }
public int top() { return top.data; } }
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
MyStack stack = new MyStack(); stack.initStack();
System.out.println("入栈操作--------------------------"); for (int i = 0; i < 6; i++) { int d = random.nextInt(10); System.out.print(d + "\t");
stack.push(d); }
System.out.println("\r\n出栈操作--------------------------"); while (!stack.isEmpty()) System.err.print(stack.pop() + "\t");