LinkedQueue链式队列方法的实现

 

使用链的方式存储节点,而不是使用数组了。

 

操作还是接口中定义的那些了。在链式的存储方式下,分写类的成员和方法的实现。

package honbaa_queue;

 

import java.util.Iterator;

 

public class LinkedQueue<T> implements Queue<T> {

 

    //仍然先定义节点类型

    private class Node{

       private T data;

       private Node next;

    }

    //成员

    private Node head;//对头,同样使用一个空的无意义节点

    private Node tail;//队尾

    //这里就要加个size了,因为haedtail没法做减法

    private int size;

   

    //构造函数

    public  LinkedQueue() {

       Node node = new Node();

       node.data = null;

       node.next = null;

       //headtail都指向这个空节点

       head = node;

       tail = node;

       size = 0;    

    }

   

   

    @Override

    public void enQueue(T element) {

       //不存在容量的问题,直接在tail后面加一个新的节点

       Node newNode = new Node();

       newNode.data = element;

       newNode.next = null;

       //挂在tail后面

       tail.next = newNode;

       //tail向后移动,head不动

       tail = tail.next;

       //size++

       size++;

    }

 

    @Override

    public T outQueue() {

       if(size()==0)

           try {

              throw new Exception("the queueis empty!");

           } catch (Exception e) {

              // TODO Auto-generatedcatch block

              e.printStackTrace();

           }

       //head后面的第一个元素除掉。

       Node first = head.next;

       head.next = first.next;

       //size--

       size--;

       return first.data;

    }

 

    @Override

    public int size() {

       return size;

    }

 

    @Override

    public boolean isEmpty() {

       if(size()==0)

           return true;

       else

           return false;

    }

 

    @Override

    public Iterator<T> iterator() {

       return new LinkedQueueIterator();

    }

    private class LinkedQueueIterator<t> implements Iterator<T>{

       //head

       private Node currentPos = head;

       @Override

       public boolean hasNext() {

           if(currentPos.next != null)

           return true;

           else

              return false;

       }

 

       @Override

       public T next() {

           // 返回下一个

           currentPos = currentPos.next;

           return currentPos.data;

       }

      

    }

    public String toString(){

       StringBuilder sb =new StringBuilder();

       Iterator it = iterator();

       while(it.hasNext())

           sb.append(it.next()+" ");

       return sb.toString();

    }

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值