队列的java实现

java

今天老师提出一个问题,就是如何用java实现队列呢?我在网上找了许多资料,发现java也是可以很轻松的实现队列。

 

如下代码:

package com;

import java.util.Collection;

import java.util.Iterator;

import java.util.Queue;

public class Aqueue implements Queue {

private Node first;

private Node last;

private int num;

public Aqueue(){

this.first = null;

this.last = null;

this.num = 0;

}

@Override

public int size() {

return this.num;

}

@Override

public boolean isEmpty() {

return false;

}

@Override

public boolean contains(Object o) {

return false;

}

@Override

public Iterator iterator() {

return null;

}

@Override

public Object[] toArray() {

return new Object[0];

}

@Override

public Object[] toArray(Object[] a) {

return new Object[0];

}

@Override

public boolean add(Object o) {

Node node = new Node();

node.data = o;

if (this.first == null){

this.first = node;

this.last = node;

}else {

this.last.setNext(node);

this.last = node;

}

this.num++;

return true;

}

@Override

public boolean remove(Object o) {

return false;

}

@Override

public boolean addAll(Collection c) {

return false;

}

@Override

public void clear() {

}

@Override

public boolean retainAll(Collection c) {

return false;

}

@Override

public boolean removeAll(Collection c) {

return false;

}

@Override

public boolean containsAll(Collection c) {

return false;

}

@Override

public boolean offer(Object o) {

return false;

}

@Override

public Object remove() {

return null;

}

@Override

//返回到第一个元素出队列

public Object poll() {

if (this.first == null){

return null;

}else {

Node n = this.first;

this.first = this.first.getNext();

n.setNext(null);

this.num--;

return n.getData();

}

}

@Override

public Object element() {

return null;

}

@Override

//返回到第一个元素,不出队列

public Object peek() {

return null;

}

private class Node{

//数据域

private Object data;

//引用域

private Node next;

public Object getData() {

return data;

}

public void setData(Object data) {

this.data = data;

}

public Node getNext() {

return next;

}

public void setNext(Node next) {

this.next = next;

}

}

}

用java自带的java.util.Queue就可以轻松实现,中间有好多方法没有实现,后期我再补上,接下来写测试类。

package test;

import com.Aqueue;

public class Test

{

public static void main(String[] args) {

Aqueue q = new Aqueue();

for (int i = 0; i < 100;i++){

q.add(i);

}

int num = q.size();

for (int i = 0; i < num;i++){

System.out.println(q.poll());

}

}

}

ok,这样就可以实现了。

如果有啥不对的,请大哥们指明,小白涉世未深,急需指导。

以上是 队列的java实现 的全部内容, 来源链接: utcz.com/z/392071.html

回到顶部