您的位置:首页 > 编程语言 > Java开发

java 实现数组队列和链表队列

2017-09-04 18:35 483 查看
package Queue;
//用数组实现自己的队列
public class Queue {
private static int DEFAULT_SIZE=100;
private Object[] queue;
private int front;
private int tail;
private int thelength;
public Queue(){
thelength=DEFAULT_SIZE;
init();
}
public Queue(int length){
thelength=length;
init();
}

public int size(){
return (front-tail+queue.length)%queue.length;
}
private void init() {
queue=new Object[thelength+1];
tail=front=0;
}

//入队列
public void put(Object e) throws Exception{
if(isFull()){
throw new Exception("队列已经满了,添加失败!");
}
queue[front]=e;
front=(front+1)%queue.length;
}

//出队列
public Object get() throws Exception{
if(isEmpty()){
throw new Exception("队列为空,删除失败!");
}
Object e=queue[tail];
queue[tail]=null;
tail=(tail+1)%queue.length;
return e;
}

//清空队列
public void clear(){
queue=null;
queue=new Object[thelength];
}

public boolean isEmpty() {
return front==tail;
}
//判断队列是否已满
public boolean isFull() {
return (front+1)%queue.length==tail;
}

public static void main(String[] args){
Queue que=new Queue(4);
char[] data=new char[]{'沧', '海','一','声'};
try {
for(int i=0;i{
E data=null;
Node next=null;
public Node(E data){
this.data=data;
}
}
public class MyLinkedListQueue{
Node head=null;
Node tail=null;

/**
* 判断队列是否为空
*/
public boolean isEmpty(){
return head==tail;
}

/**
* 往队列里面添加节点
*/
public void put(E data){
Node newnode=new Node(data);
if(head==null&&tail==null){
head=tail=newnode;
}else{
tail.next=newnode;
tail=tail.next;
}
}

/**
* 从队列里面取出节点
*/
public E get(){
if(head==null)
return null;
E e=head.data;
head=head.next;
return e;
}

/**
* 返回队列的长度
*/
public int size(){
if(head==null)
return 0;
Node temp=head;
int num=0;
while(temp!=null){
num++;
temp=temp.next;
}
return num;
}

public static void main(String[] args){
MyLinkedListQueue queue=new MyLinkedListQueue();
queue.put(4);
queue.put(3);
System.out.println("queue.size()="+queue.size()+" queue.get()="+queue.get()+"queue.size()="+queue.size());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: