首页 > 代码库 > 【数据结构】队列-数组的实现

【数据结构】队列-数组的实现

首先定义队列的基本结构,队列和栈不同之处在于队列需要两个指针,一个指向头,一个指向尾

	String[] queue;
	int front = 0;
	int rear = 0;

构造方法

	public QueueOfStrings(int capacity) {
		queue = new String[capacity];
	}

进队列

	public void enqueue(String str) {
		queue[rear++] = str;
		if (rear == queue.length)
			resize(2 * queue.length);
	}


出队列

	public String dequeue() {
		return queue[front++];
	}

判空

	public boolean isEmpty() {
		return front == rear;
	}

判满

	public boolean isFull() {
		return rear == queue.length;
	}

尺寸

	public int size() {
		return rear - front;
	}

最后附上resize

	public void resize(int capacity) {
		String[] copy = new String[capacity];
		for (int i = 0; i < rear; i++)
			copy[i] = queue[i];
		queue = copy;
	}



【数据结构】队列-数组的实现