1

我有一个任务,我必须创建一个双端队列,但是我不允许使用任何内置类或接口。我正在使用数组列表实现我的双端队列。我的问题是,例如,当我必须添加到数组列表的开头(队列的开头)时,我不允许这样做:

public void addFirst(ArrayList<Integer> array) 
{
    array.add(0, int);
}

有没有办法在不使用 add() 函数的情况下做到这一点?例如手动添加到前面并将数组的其余部分向右移动?或者也许创建一个新的数组列表并复制......我不确定。任何帮助都会很棒;我有一堆函数要编写,完成第一个函数肯定会让我朝着正确的方向前进。谢谢

4

2 回答 2

2

如果您不允许使用任何内置列表类,我怀疑您应该查看数组,而不是 ArrayList。有像System.arrayCopy这样的函数可以帮助你。

于 2012-10-19T16:20:55.230 回答
0
class ArrayList< T >
{
   private int _capacity;
   private int _size;
   private T   _data;

   ArrayList( int capacity )
   {
      _capacity = capacity;
      _size     = 0;
      _data     = new T[_capacity];
   }

   void add( T t )
   {
      if( _size < _capacity )
      {
         _data[_size++] = t;
      }
      else
      {
         // do it yourself
      }
   }

   void insert( int index, T t )
   {
      if( _size < _capacity )
      {
         System.arrayCopy( _data, index, _data, index + 1, _size - index );
         _data[_size++] = t;
      }
      else
      {
         // do it yourself
      }
   }

   ...
}
于 2012-10-19T16:43:56.320 回答