1. Use LinkedList to simulate the collection of stack data Structures and test:
The meaning of the title is:
Your own definition a collection class, within which the LinkedList simulation can be used, encapsulated into its own method using the LinkedList function method .
2. Code parsing:
(1) define own collection class Mystack, simulate stack data structure ( advanced post-out )
1 package cn.itcast_05;
2
3 import java.util.LinkedList;
4
5 / **
6 * custom stack collection
7 *
8 * @author Mr He
9 * @version V1.0
10 * /
11 public class MyStack {
12 private LinkedList link;
13
14 public MyStack () {
15 link = new LinkedList ();
16}
17
18 public void add (Object obj) {// The bottom layer calls the addFirst () method of LinkedList, which is added at the starting position each time
19 link.addFirst (obj);
20}
twenty one
22 public Object get () {// The bottom layer calls the RemoveFirst () method of LinkedList to fetch the data (pop stack). The original collection no longer contains this element.
23 // return link.getFirst ();
24 return link.removeFirst ();
25}
26
27 public boolean isEmpty () {// The bottom layer calls the LinkedList's isEmpty () method to determine whether the internal data of the collection is empty
28 return link.isEmpty ();
29}
30}
(2) test of Mystack:
1 package cn.itcast_05;
2
3 / *
4 * MyStack test
5 * /
6 public class MyStackDemo {
7 public static void main (String [] args) {
8 // create collection object
9 MyStack ms = new MyStack ();
10
11 // add element
12 ms.add ("hello");
13 ms.add ("world");
14 ms.add ("java");
15
16 // System.out.println (ms.get ());
17 // System.out.println (ms.get ());
18 // System.out.println (ms.get ());
19 // NoSuchElementException When the stack data structure is obtained, it is a pop-up (pop-out). The original data in the collection will be cleared one by one (last in, after-out). It is necessary to prevent the collection from being empty when traversing, and add judgment.
20 // System.out.println (ms.get ());
twenty one
22 while (! Ms.isEmpty ()) {
23 System.out.println (ms.get ());
twenty four }
25}
26}
The results are as follows:
Collection Framework for Java Basics Hardening Note 29: Collection code for implementing stack data structures using LinkedList (interview questions)