1、链节点
public class Node<T> { public T data; public Node next; }
2、实现代码
public class Stack<T> { private static Node bottom; //栈底指针 private static Node top; //栈顶指针 private static Integer size; //栈当前大小 /** * 初始化 */ public void initStack() { bottom = top = new Node(); top.next = bottom; size = 0; } /** * 是否空 * * @return */ public static boolean isEmpty() { if (top.next == bottom) { return true; } return false; } /** * 入栈 * * @param element */ public void pushStack(T element) { Node temp = new Node(); temp.data = element; if (top.next == bottom)//第一次入栈操作 { temp.next = bottom; top.next = temp; } else { temp.next = top.next; top.next = temp; } size++; } /** * 出栈 */ public void popStack() { if (isEmpty()) { System.out.println("栈中没有元素!"); } else { System.out.println("出栈操作:" + top.next.data + " "); top.next = top.next.next; } size--; } /** * 元素个数 * * @return :个数值 */ public int sizeStack() { return size; } /** * 查看顶部值 */ public static void getTop() { System.out.println("顶部值:" + top.next.data); } /** * * 打印放入的元素 */ public static void printStack() { Node temp = top; if (isEmpty()) { System.out.println("栈中没有元素!"); } else { for (int i = 0; i < size; i++) { System.out.print(temp.next.data + " "); temp = temp.next; } } System.out.println(); } public static void main(String[] args) { Stack<Integer> integerStack = new Stack<>(); integerStack.initStack(); integerStack.pushStack(1); printStack(); integerStack.pushStack(2); printStack(); integerStack.pushStack(3); printStack(); integerStack.pushStack(4); printStack(); integerStack.popStack(); printStack(); integerStack.pushStack(4); printStack(); integerStack.popStack(); printStack(); System.out.println("大小:" + integerStack.sizeStack()); getTop(); }
3、结果展示
1 2 1 3 2 1 4 3 2 1 出栈操作:4 3 2 1 4 3 2 1 出栈操作:4 3 2 1 大小:3 顶部值:3