论坛首页 Java企业应用论坛

java数组实现队列操作

浏览 2310 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-06-17  
package com.yin.test;

public class ArrayQueue {
	
	private int size;
	
	private int[] array;
	
	public int head = 0;
	public int tail = 0;
	
	public ArrayQueue(int size) {
		this.size = size;
		array = new int[size];
	}
	
	public void Add(int addNum) {
		if (!isFull()) {
			tail = (tail -1 + this.size)%this.size;
			array[tail] = addNum;
		} else {
			System.out.println("队列已满,不能进行插入操作");
		}
	}
	
	public void del() {
		if (!isEmpty()) {
			//tail--
			array[head] = 0;
			head = (head -1 + this.size)%this.size;
		} else {
			System.out.println("队列为空不能进行删除操作");
		}
	}
	
	public  boolean isFull() {
		int pos = (tail -1 + this.size)%this.size;
		if (pos == head) {
			return true;
		} else {
			return false;
		}
	}
	
	public boolean isEmpty() {
		if (head == tail)
			return true;
		else
			return false;
	}
	
	public void listElements() {
		//从尾部到头部输出队列元素
		int low = tail;
		int high = head;
		while (low != high) {
			System.out.print(array[low] + ",");
			low++;
		}
	}
	
	public static void main(String args[]) {
		ArrayQueue queue = new ArrayQueue(5);
		System.out.println("queue.isEmpty() = " + queue.isEmpty());
		queue.Add(1);
		System.out.println("head = " + queue.head);
		System.out.println("tail = " + queue.tail);
		queue.Add(2);
		queue.Add(3);
		queue.del();
		System.out.println("head = " + queue.head);
		System.out.println("tail = " + queue.tail);
		queue.Add(4);
		queue.Add(5);
		System.out.println("head = " + queue.head);
		System.out.println("tail = " + queue.tail);
		queue.Add(6);
		queue.listElements();
	}
	
	
}

   发表时间:2011-06-17  
不怕新手贴啊
0 请登录后投票
   发表时间:2011-06-18  
为什么用数组做内部实现,可以使用LinkedList处理起来更灵活一些吧
0 请登录后投票
   发表时间:2011-06-18  
C/C++的移民,大家理解一下
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics