数据结构----------队列
数据结构----------队列
1. 基本特点
队列是一种很重要的抽象数据结构,它具有以下两个特点:
(1)先进先出(First In First Out,FIFO)
(2)使用front和rear两个指针分别指向队头和队尾
2. 代码实现
- 基于数组的循环队列
/** * 基于数组的队列实现(循环队列) * @author Administrator * * @param <Item> */ public class ArrayQueue<Item> { private static final int CAPACITY = 10;//默认初始化容量 private Item[] items;//用数组存储数据 private int frontPtr = 0;//队头 private int rearPtr = 0;//队尾 private int size;//元素数量 public ArrayQueue(int capacity) { items = (Item[]) new Object[capacity]; } public ArrayQueue() { this(CAPACITY); } /** * 判断队列是否为空 * @return */ public boolean isEmpty() { return size == 0; } /** * 入队 * @param item */ public boolean enqueue(Item item) { if(size == items.length) { return false; } //添加元素前,判断要添加元素的tailPtr是否超过了数组的最大长度,如果超过,重置为0(循环) if((rearPtr) == items.length) { rearPtr = 0; } items[rearPtr++] = item; size++; return true; } /** * 队头删除元素 * @return */ public Item dequeue() { if(isEmpty()) { return null; } Item item = items[frontPtr]; items[frontPtr] = null;//将删掉的元素置为null size--; if((++frontPtr) == items.length) { frontPtr = 0; } return item; } /** * 从队头遍历数据 */ public void print() { if(isEmpty()) { System.out.println("队列为空"); return; } int size = this.size; int front = frontPtr; while((size--) != 0) { System.out.println(items[front++]); if(front == items.length) { front = 0; } } } }
- 基于链表的队列
import java.util.Iterator; public class LinkedQueue<Item> implements Iterable<Item> { private Node front; private Node rear; private int size; private class Node { private Item item; private Node next; public Node(Item item) { this.item = item; } } /** * * 判断队列是否为空 * @return */ public boolean isEmpty() { return size == 0; } public int size() { return size; } /** * 入队 * @param item */ public void enqueue(Item item) { Node newNode = new Node(item); if(isEmpty()) { front = newNode; }else { rear.next = newNode; } rear = newNode; size++; } /** * 出队 * @return */ public Item dequeue() { if(isEmpty()) { return null; } Item item = front.item; Node oldFront = front; front = front.next; oldFront = null; size--; return item; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { private Node current = front; @Override public boolean hasNext() { return current != null; } @Override public Item next() { Item item = current.item; current = current.next; return item; } }; } }