我有这个程序,我想在列表中插入和删除项目。我的删除功能有问题。我希望用户告诉我他们想在列表中删除哪个索引,然后减小列表的大小,然后将这些项目一起移动。例如:333 222 111 如果我删除第二个数字,那么列表看起来像 333 111 并且列表的大小将减少到 2。
提前致谢!
/* insert
* parameters:
* index -- the place in the list to insert newItem
* newItem -- the item to insert into the list
* returns:
* true -- if the item is successfully inserted
* false -- otherwise
* precondition: 0 < index
* postcondition: newItem is in postiion "index" of the list
* Algorithm: stuff
*/
bool myList::insert(int index, ListItemType newItem) {
if (!(index > 0)) {
cerr << "insert: precondition failed with index = " << index << endl;
return false;
}
if (size == MAX_LIST) {
cout << "List is full" << endl;
return false;
}
if (index > size) {
items[size] = newItem;
size++;
return true;
}
//list is not full and index is b/w items 1 and size-1
for (int i = size; i >= index; i--) {
items[i] = items[i - 1];
}
items[index - 1] = newItem;
size++;
return true;
}
bool myList::remove(int index) {
//I tried this but it doesn't work well enough
if (!(index > 0)) {
cerr << "insert: precondition failed with index = " << index << endl;
return false;
}
for (int i = size; i >= 0; i--) {
items[index] = items[index + 1];
}
size--;
return true;
}