将链表的内容放在数组引用中



我的指示是...

// Description: Places the payload contents of the list in the
//          array referenced by 'populateMeWithElements'.
// Returns the number of elements that were placed
//          in the provided memory location.
// Precondition: Enough memory has been allocated to the provided
//          memory location to hold the full contents
//          of the list.
// Postcondition: The memory allocated for 'populateMeWithElements'
//          has been deallocated after the completion of
//          this method call.
int getListElements(int* populateMeWithElements);

我写了这个...

int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
OOLNode* iterator = this->start;
int* populateMeWithElements = new int[getListSize()];
for (int i = 0; iterator->next != NULL; i++) {
populateMeWithElements[i] = iterator->payload;
iterator = iterator->next;
count++;
}
return count;
}

但我不确定它是否正确,如果是正确的......

  1. 如何在驱动程序中显示内容
  2. 我在哪里释放内存(我是在驱动程序中执行此操作还是在我编写的函数中执行此操作?

提前感谢您的任何建议或帮助。

您的函数正在声明一个隐藏输入populateMeWithElements参数的局部populateMeWithElements变量。 您正在填充本地分配的数组,根本不填充调用方的数组。

就此而言,您的函数根本不应该使用new[],因为指令清楚地指出函数的前提是调用方事先已经分配了一个足够大小的数组,并将在函数退出后释放该数组。 因此,您的函数的工作只是填充调用方的数组,仅此而已。

在这项任务中,你的循环是错误的。iterator->next != NULL需要iterator != NULL,否则如果列表为空,则iterator->next的第一次访问将失败,如果列表不为空,则将跳过尾节点的payload

试试这个:

int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
OOLNode* iterator = this->start;
for (int i = 0; iterator != NULL; i++) {
populateMeWithElements[i] = iterator->payload;
iterator = iterator->next;
++count;
}
return count;
}
OOLList list;
// populate list as needed...
int* elements = new int[list.getListSize()];
int count = list.getListElements(elements);
for(int i = 0; i < count; ++i) {
// use elements[i] as needed...
}
delete[] elements;

该功能可以进一步简化:

int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
for (OOLNode* iterator = this->start; iterator != NULL; iterator = iterator->next) {
populateMeWithElements[count++] = iterator->payload;
}
return count;
}

甚至:

int OOLList::getListElements(int* populateMeWithElements) {
int* ptr = populateMeWithElements;
for (OOLNode* iterator = this->start; iterator != NULL; iterator = iterator->next) {
*ptr++ = iterator->payload;
}
return ptr - populateMeWithElements;
}

相关内容

  • 没有找到相关文章

最新更新