package com.rao.linkList; /** * @author Srao * @className LinkedStack * @date 2019/12/3 13:59 * @package com.rao.linkList * @Description 基于链表的栈 */ public class LinkedStack { /** * 定义节点 */ static class Node{ private String data; private Node next; public Node(String data) { this.data = data; this.next = null; } public String getData() { return data; } } //栈顶元素 private Node top; /** * 入栈 * @param s */ public void push(String s){ Node node = new Node(s); if (top == null){ top = node; }else { node.next = top; top = node; } } /** * 出栈 * @return */ public Node pop(){ Node node = null; if (top.next != null){ node = top; top = top.next; }else { node = top; top = null; } return node; } public static void main(String[] args) { LinkedStack linkedStack = new LinkedStack(); linkedStack.push("aa"); linkedStack.push("11"); linkedStack.push("@@"); System.out.println(linkedStack.top.getData()); System.out.println(linkedStack.pop().getData()); System.out.println(linkedStack.pop().getData()); System.out.println(linkedStack.pop().getData()); } }
基于链表的栈和基于数组的栈不同,基于链表的栈必须自己定义节点,而基于数组的栈由数组作为节点,对于节点的定义可以使用内部类来实现,每新建一个类的实例都是新建一个新的节点