数据结构链队列java实现

相对比较简单,用到了之前写过的结点类,包含数据域和指针域

代码如下:

接口:

package queueTest;

public interface IQueue {
	public void clear();

	public boolean isEmpty();

	public int length();

	public Object peek();// 取队首元素

	public void offer(Object x) throws Exception;// 入队

	public Object poll();// 出队

	public void display();
}

链队列:

package queueTest;

import linearList.Node;

public class LinkQueue implements IQueue {

	private Node front;
	private Node rear;

	public LinkQueue() {
		front = rear = null;
	}

	@Override
	public void clear() {
		front = rear = null;
	}

	@Override
	public boolean isEmpty() {
		return front == null;
	}

	@Override
	public int length() {
		Node p = front;
		int length = 0;
		while (p != null) {
			p = p.next;
			length++;
		}
		return length;
	}

	@Override
	public Object peek() {
		if (front != null) {
			return front.data;
		} else
			return null;
	}

	@Override
	public void offer(Object x) throws Exception {
		Node p=new Node(x);
		if(front!=null){
			rear.next=p;
			rear=p;
		}
		else{
			front=rear=p;
		}
	}

	@Override
	public Object poll() {
		if (front != null) {
			Node p = front;
			front = front.next;
			if (p == rear) {
				rear = null;
			}
			return p.data;
		} else
			return null;
	}

	@Override
	public void display() {
		Node p=front;
		while(p!=null){
			System.out.printf(p.data+" ");
			p=p.next;
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值