用LinkedList模拟栈数据结构的集合

时间:2021-08-11 23:26:08
用Eclipse软件进行操作    有2种方法,左边为第一种,右边为第二种
创建class为MyStack
代码实现:
package cn_LinkedList;
 
import java.util.LinkedList;
public class MyStack {
 
//定义一个LinkedList类的成员变量
private LinkedList list;
 
public MyStack(){
list = new LinkedList();
}
public void add(Object obj){
list.addFirst(obj);
}
 
第一种:public void get(Object obj){                     第二种  public Object get() {                                                          
list.removeFirst();                                                       return list.removeFirst();
}                                                                                     }
public boolean isEmpty(){
return list.isEmpty();
}
}
 
创建class为MyStackDemo
 
package cn_LinkedList;
 
import java.util.Iterator;
import java.util.LinkedList;
 
public class MyStackDemo {
 
public static void main(String[] args) {
 
//创建一个集合
MyStack ms = new MyStack();
 
//给集合添加元素
第一种                                                                     第二种
ms.addFirst("阿三");                                               ms.add("阿三");
ms.addFirst("阿四");                                               ms.add("阿四");
ms.addFirst("阿五");                                               ms.add("阿五");
 
//遍历集合,并输出
第一种                                                                     第二种
Iterator it = list.iterator();                                      while(! ms.inEmpty()) {
while(it.hasNext()){                                               System.out.println(ms.get());
String s = (String)it.next();                                        }
System.out.println(s);                                               }
}                                                                               }
}
}