【问题标题】:How could I add an element to specific index, then move all other elements up one如何将元素添加到特定索引,然后将所有其他元素上移一个
【发布时间】:2012-09-20 15:45:42
【问题描述】:

我需要写一个

public void add(int index, int element)

如果我有这样的数组:

     element: 9 1 2 3  
     index:   0 1 2 3 4

并且参数是add(1,8)得到:

    element: 9 8 1 2 3 
    index:   0 1 2 3 4

有什么好的方法可以做到这一点?

这是我目前正在使用的:

for (int i = actualSize; i >= 0; i--)
       {
           if (i != index)
           {
               data[i] = data[i-1];
           }
           else if (i == index)
               data[i] = element;
       }

但如果调用:add(1, 8),我会得到以下输出:

     element: 9 8 1 2  
     index:   0 1 2 3 4

【问题讨论】:

  • 根据您使用的语言,有一些容器可以在后台为您处理。

标签: arrays collections element


【解决方案1】:

我认为您的函数存在逻辑错误。是否要移动插入索引下方的元素?看起来这就是你正在做的事情。

对于您的循环,以下内容如何:

// make sure that extra space for data[] is allocated

for (int i = maxIndexBeforeInsert; i >= insertAtThisIndex; i--)
{
    data[i+1] = data[i];
}

data[insertAtThisIndex] = element;

【讨论】:

    【解决方案2】:

    可能是这样的:

    for (int i = actualSize-1; i>0 && i>index; i--)
    {
        data[i] = data[i-1];
    }
    data[index] = element;
    

    但这取决于空元素的含义,例如初始数组末尾的那个。

    后面的会被覆盖,但是,不管它们是什么意思,其他位置的那些“空值”将像正常值一样被移动。这可能是您需要的,也可能不是。

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 2022-12-22
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多