Java实现队列

1.基于数组实现队列

注意:基于数组实现的队列会有假满的问题,可以使用循环队列解决

package wd;
class queue{
	public int front;
	public int rear;
	public String[] data;
	public queue() {
		data=new String[10];
		front=0;
		rear=0;
	}
	public void add(String element) {
		if(full()) {
			return;
		}
		data[rear]=element;
		rear++;
		
	}
	public void remove() {
		if(empty()) {
			return;
		}
		data[front]=null;
		front++;
		
	}
	public int length() {
		return rear-front;
		
	}
	public boolean empty() {
		if(rear==front&&rear==0) {
			System.out.println("empty");
			return true;
		}
		return false;
		
	}
	public boolean full() {
		if(rear==front&&rear==10) {
			System.out.println(" not full");
			return true;
		}
		if(rear!=front&&rear==10) {
			System.out.println("full");
			return true;
		}
		return false;
	}
	
}
public class arrayqueue {
	public static void main(String[] args) {
		queue wr=new queue();
		wr.add("test1");
		wr.add("test 2");
		System.out.println(wr.length());
		
	}

}

2.基于链表的队列

package wd;
class wdNode{
	public wdNode next;
	public String data;
	public wdNode(String data) {
		this.data=data;
		this.next=null;
	}
}
class linqueue{
	public wdNode front;
	public wdNode rear;
	public int size;
	public linqueue() {
		front=null;
		rear=null;
	}
	public void add(String element) {
		if(full()) {
			return;
		}
		wdNode newdata=new wdNode(element);
		if(front==null) {
			front=newdata;
			rear=newdata;
		}
		else {
			rear.next=newdata;
			rear=newdata;
		}
		size++;
		
	}
	public void remove() {
		if(empty()) {
			return;
		}
		wdNode oldfront=front;
		front=front.next;
		oldfront.next=null;
		size--;
		
		
	}
	public int length() {
		return size;
		
	}
	public boolean empty() {
		if(rear==front) {
			System.out.println("empty");
			return true;
		}
		return false;
		
	}
	public boolean full() {
		return false;
	}
	
}
public class linkqueue {
	public static void main(String[] args) {
		linqueue wr=new linqueue();
		wr.add("test1");
		wr.add("test 2");
		System.out.println(wr.length());
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值