1.使用LinkedList实现Stack栈
根据接口Stack ,实现类:MyStack,并向这个栈中,压入5个英雄,接着弹出5个英雄
1 package Collection; 2 3 import java.util.LinkedList; 4 import java.util.List; 5 6 import charactor.Hero; 7 /* 8 * 使用LinkedList实现Stack栈 9 */ 10 public class MyStack implements Stack { 11 //使用static便于打印栈中各个元素 12 static LinkedList<Hero> ll = new LinkedList<>(); 13 14 @Override 15 public void push(Hero h) { 16 // TODO Auto-generated method stub 17 ll.addLast(h); 18 } 19 20 @Override 21 public Hero pull() { 22 // TODO Auto-generated method stub 23 return ll.removeLast(); 24 } 25 26 @Override 27 public Hero peek() { 28 // TODO Auto-generated method stub 29 return ll.getLast(); 30 } 31 32 public static void main(String[] args) { 33 MyStack ms=new MyStack(); 34 for(int i=0;i<5;i++){ 35 ms.push(new Hero("Hero "+i)); 36 } 37 System.out.println("原本栈中元素分别是:"+ll); 38 for(int i=0;i<5;i++){ 39 System.out.println("出栈:"+ms.pull().name); 40 System.out.printf("出栈后,此时栈中元素分别是:"+ll+" "); 41 } 42 43 } 44 }
效果图