简体   繁体   English

如何仅在给定已实现的方法的情况下创建队列?

[英]How can I create a queue only given the implemented methods?

I have a class MyList with the following methods :我有一个 MyList 类,具有以下方法:

public class MyList{
  ArrayList<Object> list;

  MyList(int a, int b)
  {
     list = new ArrayList<Object>();
     for(;a<=b;a++)
        list.add(a);
  }
  public void add(int index, Object o)
  {
     list.add(index, o);
  }
  public Object remove(int index) throws isEmptyException
  {
     if(isEmpty())
        throw new isEmptyException();
     else
        return list.remove(index);
  }
  public boolean isEmpty()
  {
    return list.isEmpty();
  }

Here's my Class Queue.这是我的课程队列。 I have to implement the following methods using only the above methods from MyList.我必须仅使用 MyList 中的上述方法来实现以下方法。

public class Queue extends MyList{

  public void enqueue(Object o)
  {
   //adds a new Object to the queue
  }
  public Object dequeue()
  {
   //removes the next Object from the queue and returns it
  }
  public boolean empty()
  {
   //Checks if the queue is empty
  }

I don't really know where to start here, since I don't know the size of the queue.我真的不知道从哪里开始,因为我不知道队列的大小。 Can someone give me a hint how to solve this?有人可以给我一个提示如何解决这个问题吗? Is a recursive method useful here?递归方法在这里有用吗?

Thanks in advance!提前致谢!

Call the add or remove inside the enqueue and dequeue methods of the Queue class, maintain a pointer to first and last.在Queue类的入队和出队方法中调用add或remove,维护一个指向first和last的指针。

 public class Queue extends MyList {
    private int index;
    private int firstIndex;

    Queue(int a, int b)
    {
        super(a, b);
    }
    public void enqueue(Object o)
    {
        add(o);
        index++;
    }
    public Object deueue() throws Exception {
        if(firstIndex == index || isEmpty()) {
            firstIndex =0; index =0;
            throw new Exception("");
        }
        else
            return list.remove(++firstIndex);
    }
    public boolean isEmpty()
    {
        return list.isEmpty();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM