Using removeLast and removeFrist to simulate heap and stack, lastfrist
/*
* Not long ago, I decided to learn Java by myself and pay attention to many public accounts and microblogs. A few days later I saw a joke:
* The child cried at night, and my wife asked me to check it out.
* I said, "No, our bed is a queue. You have to go to bed first...
* The wife said: NO No, it is a stack.
* Then, I put my foot on my ass.
* At that time, I read comments, saying that programmers and couples had a lot of fun, and I also checked the stack knowledge online,
* Not professional in computer science, but also in the fog. Today is the second round of basic knowledge Review,
* If you have a method to simulate a stack on the consumer list, you can get started to understand the true meaning of this joke,
* I feel more and more happy with the charm of the programming language.
*/
1 import java. util. optional list; 2 3 public class NoNo {4 public static void main (String [] args) {5 MyQueue q = new MyQueue (); 6 q. add ("My wife goes to bed first"); 7 q. add ("My wife goes to bed"); 8 9 while (q. isEmpty () = false) {10 11 System. out. println (q. get2 () + "get out of bed and coax bear child"); 12 13} 14 15} 16} 17 18 class MyQueue {19 private queue List; // underlying 20 21 MyQueue () {22 List = new upload List (); 23} 24 25 public void add (Object obj) {26 List. addFirst (obj); 27} 28 public Object get2 () {29 // simulate stack 30 return List. removeFirst (); 31} 32 33 public boolean isEmpty () {34 return List. isEmpty (); 35} 36}
PutOut: I went to bed after my wife, but I had to get out of bed.
1 import java. util. optional list; 2 3 public class NoNo {4 public static void main (String [] args) {5 MyQueue q = new MyQueue (); 6 q. add ("My wife goes to bed first"); 7 q. add ("My wife goes to bed"); 8 9 while (q. isEmpty () = false) {10 11 System. out. println (q. get () + "get out of bed and coax bear child"); 12} 13 14} 15} 16 17 class MyQueue {18 private queue List; // underlying 19 20 MyQueue () {21 List = new jsonlist (); 22} 23 24 public void add (Object obj) {25 List. addFirst (obj); 26} 27 28 public Object get () {29 // simulates the 30 return List of the queue. removeLast (); 31} 32 33 public boolean isEmpty () {34 return List. isEmpty (); 35} 36}
OutPut: My wife goes to bed first, but she wants to get out of bed.
Additional knowledge:
Source code: