Java-实现队列的基本操作

原创
2018/05/01 15:25
阅读数 2.2K

Queue.java

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.java

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("队列已清空!!");

	}

}

运行结果如下:

输入图片说明

展开阅读全文
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部