基于链式结构的栈实现

    xiaoxiao2021-03-25  94

    package com.newer.array; /** * 基于链式结构的栈实现 * * @author Administrator */ public class MyStackLink<E> { // 定义一个长度是0的链表 Node head = null; int length;// 结点个数 // 将数据压入栈中 public void push(E e) { // 创建结点对象 Node n = new Node(e); // 每次都将新的结点作为新的头结点 n.next = head; head = n; length++; } // 查看栈顶的数据 public E get() { return head == null ? null : head.e; } // 弹出栈顶的数据 public E poll() { if (head == null) { return null; } // 如果头结点存在,就取出并移除头结点 Node n = head; head = n.next; n.next = null; length--; return n.e; } // 获得栈的大小 public boolean isEmpty() { return length == 0; } // 链式结构的结点类 private class Node { E e; Node next; public Node(E e) { this.e = e; } } }

    package com.newer.array; import java.util.Stack; public class Demo { public static void main(String[] args) { // MyStackLink<String> stack = new MyStackLink<String>(); Stack<String> stack = new Stack<String>(); //将数据压入栈 stack.push("AA"); stack.push("BB"); stack.push("CC"); stack.push("DD"); while(!stack.isEmpty()){ String s = stack.pop(); System.out.println(s); } // //查看栈顶的数据 // String s = stack.get(); // System.out.println(s); // // //弹出栈顶的数据 // String s1 = stack.poll(); // System.out.println(s1); // // s = stack.get(); // System.out.println(s); } }

    转载请注明原文地址: https://ju.6miu.com/read-14666.html

    最新回复(0)