Java-實現隊列的基本操做

Queue.javajava

package com.wanali.java_ds.sqqueue;

public interface Queue {
	public void clear();

	public boolean empty();

	public int length();

	public void offer(Object x);// 差人元素到對列中

	public Object pop();// 刪除隊首元素

	public Object peek();// 取隊首元素並返回

	public void display();
}

SqQueue.java函數

package com.wanali.java_ds.sqqueue;

public class SqQueue implements Queue {
	public int front;
	public int rear;
	public Object elem[];

	// 構造函數
	public SqQueue(int maxsize) {
		front = rear = 0;
		elem = new Object[maxsize];
	}

	public void clear() {
		// TODO Auto-generated method stub
		front = rear = 0;
	}

	public boolean empty() {
		// TODO Auto-generated method stub
		return front == rear;
	}

	public int length() {
		// TODO Auto-generated method stub
		return rear - front;
	}

	public void offer(Object x) {
		// TODO Auto-generated method stub
		elem[rear] = x;
		rear++;
	}

	public Object pop() {
		// TODO Auto-generated method stub

		Object t = elem[front];
		front++;
		return t;

	}

	public Object peek() {
		// TODO Auto-generated method stub
		return elem[front];
	}

	public void display() {
		int i = front;
		// TODO Auto-generated method stub
		while (i < rear) {
			System.out.println(elem[i]);
			i++;

		}
	}

}

TestSqQueue.javacode

package com.wanali.java_ds.sqqueue;

public class TestSqQueue {
	public static void main(String[] args) {
		SqQueue sqQueue = new SqQueue(10);
		sqQueue.offer(1);
		sqQueue.offer(2);
		sqQueue.offer(3);
		sqQueue.offer(4);
		sqQueue.display();
		System.out.println("判斷隊列是否爲空:" + "\n" + sqQueue.empty());
		System.out.println("刪除隊首元素:" + "\n" + sqQueue.pop());
		System.out.println("取隊首元素:" + "\n" + sqQueue.peek());
		System.out.println("隊列的長度爲:" + "\n" + sqQueue.length());
		System.out.println("清空對列:");
		sqQueue.clear();
		sqQueue.display();
		System.out.println("隊列已清空!!");

	}

}

運行結果以下:隊列

輸入圖片說明

相關文章
相關標籤/搜索