数据结构之java实现链式队列(三)

前两篇文章采用数组形式构造队列,现在用链表构造队列

链式队列基本上和链表类似,基本如下:

rear指针始终指向链表最后一个元素

front指针始终指向链表第一个元素

代码如下:

public class LinkQueue<T> {
	
	private Node front;//队头指针
	private Node rear;//队尾指针
	private int size = 0;
	
	public LinkQueue(){
		
		
	}
	//-----进入队列算法-------
	public boolean enQueue(T data){
		
		if(data == null)
			return false;
		Node node = new Node(data);
		
		if(front == null){
			front = node;
			rear = front;
			size++;
		}else{
			
			rear.next = node;
			rear = rear.next;
			size++;
		}
		return true;
	}
	//------出队列算法---------
	public T deQueue() throws Exception{
		
		if(front == null)
			throw new Exception("LinkQueue is empty ");
		T ret = front.data;
		front = front.next;
		size--;
		return ret;
	}
	//------队列中元素个数-----------
	public int getSize(){
		return size;
	}
	
	//-------判断队列是否为空------------
	public boolean isEmpty(){
		
		return (front == null)? true:false;
	}
	
	//------打印队列------------
	public void display() throws Exception{
		
		if(isEmpty())
			throw new Exception("LinkQueue is empty ");
		Node current = front;
		while(current != null){
			
			System.out.println(current.data);
			current = current.next;
		}
		
		
	}
	
	
	
	
	
	
	
	class Node{
		
		T data;
		Node next;
		public Node(){}
		public Node(T data){
			
			this.data = data;
		}
		
	}

	
	public static void main(String[] args) throws Exception{
		
		
		LinkQueue linkQueue = new LinkQueue();
		for(int i=1;i<=100;i++)
			linkQueue.enQueue(i);
		System.out.println("元素数量:"+ linkQueue.getSize());
		System.out.println("**************************");
		for(int i=1;i<=99;i++)
			linkQueue.deQueue();
		System.out.println("元素数量:"+ linkQueue.getSize());
		System.out.println("**************************");
		for(int i=101;i<=200;i++)
			linkQueue.enQueue(i);
		System.out.println("元素数量:"+ linkQueue.getSize());
		System.out.println("**************************");
		
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值