java 集合框架-利用LinkedList实现堆栈数据结构

/*
利用LinkedList来实现队列(先进先出)和堆栈(先进后出)
堆栈:后进先出
队列:先进先出
*/

import java.util.*;
/*队列:将LinkedList进行封装,实现队列先进先出的功能特点*/
class Duilie      
{
	private LinkedList link;

	Duilie()
	{
		link=new LinkedList();
	}

	public void myAdd(Object obj)
	{
		link.addFirst(obj);
		sop(link.getFirst());
	}

	public Object myGet()
	{
		return link.removeLast();
	}

	public boolean isEmpty()
	{
		return link.isEmpty();
	}

	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}


/*
堆栈:将LinkedList进行封装,实现堆栈后进先出的功能特点
*/

class Duizhan
{
	private LinkedList link;
	Duizhan()
	{
		link=new LinkedList();
	}
	
	public void myAdd(Object obj)
	{
		link.addFirst(obj);
		sop(link.getFirst());
	}

	public Object myGet()
	{
		return link.removeFirst();
	}
	
	public boolean isEmpty()
	{
		return link.isEmpty();
	}
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

}
class  LinkedListTest
{
	public static void main(String[] args) 
	{
		duiLie();
		duizhan();
	}

	public static void duiLie()
	{
		Duilie dl=new Duilie();
		sop("-------------------队列---------------------");
		dl.myAdd("Hello..1");
		dl.myAdd("Hello..2");
		dl.myAdd("Hello..3");
		dl.myAdd("Hello..4");
		sop("队列出的顺序");
		//sop(dl);
		while(!dl.isEmpty())
		{
			sop(dl.myGet());
		}
		sop("---------------------end-------------------");
	}

	public static void duizhan()
	{
		Duizhan dz=new Duizhan();
		sop("-------------------堆栈---------------------");
		dz.myAdd("Hello..1");
		dz.myAdd("Hello..2");
		dz.myAdd("Hello..3");
		dz.myAdd("Hello..4");
		sop("堆栈出的顺序");
		//sop(dz);
		while(!dz.isEmpty())
		{
			sop(dz.myGet());
		}
		sop("---------------------end-------------------");
	}

	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}

你可能感兴趣的:(java,堆栈,LinkedList)