栈的实现:
package linear.stack; import java.lang.reflect.Array; /** * @Description: 栈的实现 * @Auther: Weijie.Zhang * @Date: 2018/11/2 16:56 */public class Stack<T> { private final static int DEFAULT_SIZE = 10; private T[] array; private int count; public Stack(int size, Class<T> type) { count = 0; array = (T[]) Array.newInstance(type, size); } public Stack(Class<T> type) { this(DEFAULT_SIZE, type); } //添加元素 public T push(T value) { array[count] = value; count++; return value; } //删除元素 public T pop() { return array[--count]; } //返回栈顶元素值 public T pick() { return array[count - 1]; } //返回栈大小 public int size() { return count; } //返回栈是否为空 public Boolean isEmpty() { return this.size() > 0 ? true : false; } //打印栈 public void printStack() { if (!this.isEmpty()) { System.out.println("空栈"); } for (int i = size() - 1; i > 0; i--) { System.out.print(array[i] + " "); } } } 测试:
package linear.stack; /** * @Description: TODO * @Auther: Weijie.Zhang * @Date: 2018/11/2 17:14 */public class MainTest { public static void main(String[] args) { Stack<Integer> stack = new Stack(Integer.class); stack.printStack(); for (int i = 0; i < 10; i++) { stack.push(i + 22); } System.out.println(stack.size()); System.out.println(stack.pick()); stack.pop(); System.out.println(stack.size()); stack.push(10000); stack.printStack(); }}
原文地址:https://www.cnblogs.com/qugemingzihaonan13/p/9897426.html
时间: 2024-10-29 05:34:48