package packageExercise;
import java.util.LinkedList;
import java.util.ListIterator;
//栈
class Stack{
LinkedList linkedList;
public Stack() {
this.linkedList = new LinkedList();
}
//进栈
public void add(Object object){
linkedList.push(object);
}
//出栈
public Object delete(){
return linkedList.pop();
}
public int size() {
return linkedList.size();
}
}
//堆
class Heap{
LinkedList linkedList;
public Heap() {
this.linkedList = new LinkedList();
}
public void add(Object object) {
linkedList.offer(object);
}
public Object delete() {
return linkedList.poll();
}
public int size() {
return linkedList.size();
}
}
public class Demo1 {
public static void main(String[] args) {
//栈
Stack stack = new Stack();
stack.add("第一个人");
stack.add("第二个人");
stack.add("第三个人");
stack.add("第四个人");
stack.add("第五个人");
int size = stack.size();
for(int i = 0;i < size;i++)
{
System.out.println(stack.delete());
}
System.out.println("--------------------");
//堆
Heap heap = new Heap();
heap.add("第一个人");
heap.add("第二个人");
heap.add("第三个人");
heap.add("第四个人");
heap.add("第五个人");
int length = heap.size();
for(int i =0;i < length ; i++)
{
System.out.println(heap.delete());
}
}
}
小记:用LinkList模仿栈和堆的数据结构
最新推荐文章于 2022-07-10 09:17:12 发布