java 用单链表实现队列

public class LinkQueue<T> 
{
	class Node<T>
	{
		private T data;//数据域
		private Node<T> next;//引用域
		public Node() 
		{
			this.data=null;
			this.next=null;
		}
		public Node(T data)
		{
			this.data=data;
			this.next=null;
		}
		public void setNext(Node<T> t)
		{
			this.next=t;
		}
		public T getData()
		{
			return this.data;
		}
		public Node<T> getNext()
		{
			return this.next;
		}
	}
	private Node<T> head;//队头
	private Node<T> tail;//队尾
	public LinkQueue()
	{
		this.head=null;
		this.tail=null;
	}
	//入队
	public boolean inQueue(T t)
	{
		Node<T> p=new Node<T>(t);//生成一个结点
		if(head==null)//如果头等于空
		{
			head=p;//头引用指向这个结点
			tail=p;//尾引用指向这个结点
		}
		else 
		{
			tail.next=p;//插入尾部
			tail=p;//尾引用指向新的尾结点
		}
		return true;
	}
	//dream it possible
	//出队
	public T outQueue()
	{
		if(head==null) return null;
		else 
		{
			T t=head.getData();//取下对队头
			head=head.next;//头引用后移
			return t;
		}
			
	}
	//查队头
	public T peek()
	{
		if(head==null) return null;
		else
			return head.getData();
	}
	//判空
	public boolean isEmpty()
	{
		return head==null;
	}
}

测试:

public class LinkQueueTest {
	public static void main(String[] args) {
		LinkQueue<Integer> linkQueue=new LinkQueue<Integer>();
		//入队5个
		for(int i=0;i<5;i++)
		{
			linkQueue.inQueue(i);
		}
		//出栈测试
		for(int i=0;!linkQueue.isEmpty();i++)
		{
			System.out.println(linkQueue.peek()+"  "+linkQueue.outQueue());
		}
//		for(int i=0;i<8;i++)
//		{
//			System.out.println(linkQueue.peek()+"  "+linkQueue.outQueue());
//		}

	}
}
结果:

0  0
1  1
2  2
3  3
4  4


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值