栈
基于链表
package info.zh93.DS;/** * Created by zhanghao on 2016.09.23. */public class StackClass { public class Node{ public String data; public Node before; public Node(String data) { this.data = data; } public Node(String data, Node before) { this.data = data; this.before = before; } } //根节点 private Node last = null; //压入栈中 public void push(String data){ if (last == null){ last = new Node(data, null); return; } Node inner = new Node(data, last); last = inner; } //弹出 public String pop() throws Exception { if (last != null){ Node node = last; last = last.before; return node.data; } return null; } public void printStack(){ Node node = last; while (node != null){ System.out.println(node.data); node = node.before; } } public static void main(String[] strs) throws Exception { StackClass sc = new StackClass(); for (int i = 0; i < 10; i++){ sc.push(i + ""); System.out.println("pop: " + sc.pop()); } sc.printStack(); }}
基于数组