2 回答

TA貢獻1803條經驗 獲得超3個贊
這個想法是從第一個元素到最后一個循環遍歷數組,尋找第一次出現的 0。如果沒有找到,則數組已滿。如果這樣做,請使用System.arraycopy將所有內容從 0 向右移動到標識的位置 1,然后在位置 0 處插入新元素。
public void addElementsToArray(int element){
for(int i=0; i<array.length; i++)
{
if(array[i] == 0)
{
System.arraycopy(array, 0, array, 1, i);
array[0] = element;
return;
}
}
throw new IllegalStateException("Array is full");
}

TA貢獻1827條經驗 獲得超8個贊
出于您的目的,數組不是用戶的最佳數據結構,而是使用隊列。
LinkedList<Integer> q = new LinkedList<>(); // LinkedList implements Queue interface
q.addFirst(5); // will add element 5 at first position
q.addLast(6); // will add element 6 at lastposition
int f = q.pollFirst(); // will give element at first position
int l = q.pollLast(); // will give element at lastposition
int ele= q.get(0); // will give element at 0 index
Queue 用于在隊列末尾插入元素并從隊列開頭刪除元素。它遵循先進先出的概念。
添加回答
舉報