首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构----队列

数据结构----队列

作者头像
SuperHeroes
发布2018-05-30 17:44:43
2860
发布2018-05-30 17:44:43
举报
文章被收录于专栏:云霄雨霁云霄雨霁云霄雨霁

我们可以设计一个队列API(泛型实现):

public class Queue<Item> implements Iterable<Item>                Queue()                     创建空队列        void enqueue()                 添加一个元素        Item dequeue()                 删除最早添加的一个元素   boolean isEmpty()                  队列是否为空            int size()                         队列中的元素数量

使用链表实现队列(实现了迭代器):

public class Queue<Item> implements Iterable<Item> { //实现迭代器接口
    //持有一个头指针一个尾指针,方便进队和出队。
    private Node<Item> first,last; 
    private int n;  //保存队列中的元素个数       
    //节点类
    private static class Node<Item> {           
        private Item item;
        private Node<Item> next;
    }
    //构造器
    public Queue() {first = null;last  = null;n = 0;}
    //是否为空    
    public boolean isEmpty() {  return first == null;  }
    //当前元素个数
    public int size() {return n;}
    //入队列
    public void enqueue(Item item) { 
        Node<Item> oldlast = last;
        last = new Node<Item>();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else           oldlast.next = last;
        n++;
    }
    //出队列
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = first.item;
        first = first.next;
        n--;
        if (isEmpty()) last = null;  
        return item;
    }

    //创建迭代器
    public Iterator<Item> iterator()  {
        return new ListIterator<Item>(first);  
    }
    //实现迭代器
    private class ListIterator<Item> implements Iterator<Item> {
        private Node<Item> current;
        public ListIterator(Node<Item> first) {
            current = first;
        }
        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }
        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.12.10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档