Use LinkedList to simulate the collection class of the stack data structure and test
1. Topic
Please use LinkedList to simulate a collection of stack data structures and test.
The meaning of the title is: You define a collection class yourself, so that the collection class behaves like a stack data structure, and LinkedList can be used inside this collection class.
2. Code demonstration
(1) Define the collection class
package cn.itcast_05; import java.util.LinkedList; public class MyStack { private LinkedList link; public MyStack () { link = new LinkedList(); } public void add(Object obj) { link.addFirst(obj); } public Object get() { return link.removeFirst(); } public boolean isEmpty() { return link.isEmpty(); } }
(2) Test collection class
package cn.itcast_05; public class MyStackDemo { public static void main(String[] args) { // create collection object MyStack ms = new MyStack (); // add element ms.add("hello"); ms.add("world"); ms.add("java"); while(!ms.isEmpty()){ System.out.println(ms.get()); } } }