数据结构③-队列

来源:互联网 发布:python 自动测试框架 编辑:程序博客网 时间:2024/06/03 21:35

不重复发明轮子,自娱自乐。

实际开发中队列用LinkedList

本文大部分来自转载

原地址:http://blog.csdn.net/lcore/article/details/8868078

public class QueueDemo<T> {private T[] data;private int size;           //元素个数private int front;          //队头private int rear;           //队尾private QueueDemo(){this(10);}private QueueDemo(int size){data = (T[]) new Object[size];front = 0;rear = 0;size = 0;}//队尾插入一个元素public boolean add(T t){if(isFull()){resize();front = 0;}//直接用size-1 不妥rear = (front + size) % data.length; data[rear] = t;size++;return false;}//获取但不移除队头public Object peek(){return data[front];}//移除队头public T remove(){if(isEmpty()){throw new RuntimeException("队列为空.");}T tempObj = data[front];data[front] = null;//front++;front = (front + 1) % (data.length); //有必要么?循环队列?size--;return tempObj;}//判断队列是否为空public boolean isEmpty(){return size == 0;}//判断队列是否已满public boolean isFull(){return size == data.length;}/** * 扩容 * 注意重新扩容时并不需要去设置size */public void resize(){T[] tmp = (T[]) new Object[data.length * 2];//从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。System.arraycopy(data, 0, tmp, 0, size);data = tmp;tmp = null;   //引用置为空 便于gc处理}public static void main(String[] args){QueueDemo<String> q = new QueueDemo<String>();q.add("a");    q.add("b");    q.add("c");    q.add("d");    q.add("e");    q.add("f");    q.add("g");    q.add("h");    q.add("i");    q.add("j");         q.add("k");    q.add("l");    q.add("m");    while( !q.isEmpty() ){        String temp = q.remove();        System.out.println(temp);    }}}

队列的链表实现

public class LinkQueue<T> {private Node head;private Node rear;private int size;public LinkQueue(){head = null;rear = null;size = 0;}class Node{T data;Node next;public Node(){//无参构造}public Node(T t){this.data = t;}}/** * 从队列的尾部插入节点 * @param t */public void add(T t){Node node = new Node(t);if(isEmpty()){head = node;rear = head;}else{rear.next = node;}rear = node;size++; //队列长度加1}/** * 从队列头部删除 * @return */public T remove(){T tmp = null;if(isEmpty()){throw new NullPointerException("队列是空的.");}if(null == head.next)rear = null;tmp = head.data;head = head.next;size--;return tmp;}public int size(){return size;}public boolean isEmpty(){return head == null;}public T front(){if(null != head)return head.data;return null;}public static void main(String[] args){LinkQueue<String> q = new LinkQueue<String>();q.add("a");    q.add("b");    q.add("c");    q.add("d");    q.add("e");    q.add("f");    q.add("g");    q.add("h");    q.add("i");    q.add("j");         q.add("k");    q.add("l");    q.add("m");    while( !q.isEmpty() ){        String temp = q.remove();        System.out.println(temp);    }}}


0 0
原创粉丝点击