分享

编写一个JAVA的队列类

 N_once 2007-07-30

  队列是设计程序中常用的一种数据结构。它类似日常生活中的排队现象,采用一种被称为“先进先出”(LIFO)的存储结构。数据

  队列是设计程序中常用的一种数据结构。它类似日常生活中的排队现象,采用一种被称为“先进先出”(LIFO)的存储结构。数据元素只能从队尾进入,从队首取出。在队列中,数据元素可以任意增减,但数据元素的次序不会改变。每当有数据元素从队列中被取出,后面的数据元素依次向前移动一位。所以,任何时候从队列中读到的都是队首的数据。


  根据这些特点,对队列定义了以下六种操作:
  enq(x) 向队列插入一个值为x的元素;
  deq() 从队列删除一个元素;
  front() 从队列中读一个元素,但队列保持不变;
  empty() 判断队列是否为空,空则返回真;
  clear() 清空队列;
  search(x) 查找距队首最近的元素的位置,若不存在,返回-1。

  Vector类是JAVA中专门负责处理对象元素有序存储和任意增删的类,因此,用Vector
  可以快速实现JAVA的队列类。元素只能从队尾进入,从队首取出。在队列中,数据元素可以任意增减,但数据元素的次序不会改变。每当有数据元素从队列中被取出,后面的数据元素依次向前移动一位。所以,任何时候从队列中读到的都是队首的数据。


  根据这些特点,对队列定义了以下六种操作:
  enq(x) 向队列插入一个值为x的元素;
  deq() 从队列删除一个元素;
  front() 从队列中读一个元素,但队列保持不变;
  empty() 判断队列是否为空,空则返回真;
  clear() 清空队列;
  search(x) 查找距队首最近的元素的位置,若不存在,返回-1。

  Vector类是JAVA中专门负责处理对象元素有序存储和任意增删的类,因此,用Vector
  可以快速实现JAVA的队列类。

 
import java.util.*;
public class BroadCastQueue extends Vector {//向量的子类
 public BroadCastQueue(){
  super();
 }
 
public synchronized void enq(Object x) {
super.addElement(x);
}
public synchronized Object deq() {
/* 队列若为空,引发EmptyQueueException异常 */
if( this.empty() )
throw new EmptyQueueException();
Object x = super.elementAt(0);
super.removeElementAt(0);
return x;
}
public synchronized Object front() {
if( this.empty() )
throw new EmptyQueueException();
return super.elementAt(0);
}
public boolean empty() {
return super.isEmpty();
}
public synchronized void clear() {
super.removeAllElements();
}
public int search(Object x) {
return super.indexOf(x);
}
}
 
import java.util.*;
public class BroadCastQueue extends Vector {//向量的子类
 public BroadCastQueue(){
  super();
 }
 
public synchronized void enq(Object x) {
super.addElement(x);
}
public synchronized Object deq() {
/* 队列若为空,引发EmptyQueueException异常 */
if( this.empty() )
throw new EmptyQueueException();
Object x = super.elementAt(0);
super.removeElementAt(0);
return x;
}
public synchronized Object front() {
if( this.empty() )
throw new EmptyQueueException();
return super.elementAt(0);
}
public boolean empty() {
return super.isEmpty();
}
public synchronized void clear() {
super.removeAllElements();
}
public int search(Object x) {
return super.indexOf(x);
}
}
 
 
import java.lang.*;
public class EmptyQueueException extends RuntimeException{
 public EmptyQueueException(){
  
 }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多