删除 ArrayList 中最右边的元素
removing the right most elements in ArrayList
我想删除列表的最右半部分,但这段代码有时可以,但有时不行。
如果l包含A → B → C → D → E
,则调用后
l.removeRightmostHalf()
,l 变为A → B → C
。
public void removeRightmostHalf() {
if (size % 2 != 0)
{
current = (size / 2) + 1;
while(current <= size)
{
for (int i = current + 1; i < size; i++)
nodes[i-1] = nodes[i];
size--;
if (size == 0)
current = -1;
else if (current == size)
current = 0;
}
}
else
{
current = (size / 2);
while(current <= size)
{
for (int i = current + 1; i < size; i++)
nodes[i-1] = nodes[i];
size--;
if (size == 0)
current = -1;
else if (current == size)
current = 0;
}
}
}
此代码可以完成工作,请尝试并告诉我。
如果我的回答对你来说是正确的,请不要忘记select它作为正确答案。
public void removeRightmostHalf() {
if (size % 2 != 0)
size=(size / 2)+1;
else size=(size / 2);
}
这是怎么做到的?
因为问题是删除右边的一半,所以将大小减半,这将使数组的右边部分无法访问,就像 Arraylist.Remove() 所做的那样。
public void removeRightmostHalf()
{
if (size % 2 != 0)
current = (size / 2) + 1;
else
current=size/2;
nodes.subList(current,size).clear()
}
我想删除列表的最右半部分,但这段代码有时可以,但有时不行。
如果l包含A → B → C → D → E
,则调用后
l.removeRightmostHalf()
,l 变为A → B → C
。
public void removeRightmostHalf() {
if (size % 2 != 0)
{
current = (size / 2) + 1;
while(current <= size)
{
for (int i = current + 1; i < size; i++)
nodes[i-1] = nodes[i];
size--;
if (size == 0)
current = -1;
else if (current == size)
current = 0;
}
}
else
{
current = (size / 2);
while(current <= size)
{
for (int i = current + 1; i < size; i++)
nodes[i-1] = nodes[i];
size--;
if (size == 0)
current = -1;
else if (current == size)
current = 0;
}
}
}
此代码可以完成工作,请尝试并告诉我。 如果我的回答对你来说是正确的,请不要忘记select它作为正确答案。
public void removeRightmostHalf() {
if (size % 2 != 0)
size=(size / 2)+1;
else size=(size / 2);
}
这是怎么做到的? 因为问题是删除右边的一半,所以将大小减半,这将使数组的右边部分无法访问,就像 Arraylist.Remove() 所做的那样。
public void removeRightmostHalf()
{
if (size % 2 != 0)
current = (size / 2) + 1;
else
current=size/2;
nodes.subList(current,size).clear()
}