gpt4 book ai didi

c++ - 从链表中释放内存

转载 作者:行者123 更新时间:2023-11-30 04:00:19 25 4
gpt4 key购买 nike

我正在尝试删除第 n 个元素,它是从 1 到 n 的随机数。我的代码做得很好(删除了正确的元素并且连接了周围的元素)但是当谈到效率时,当我取消注释 delete (nodeToRemove); 行时它崩溃了,我是不知道为什么。有没有人有任何见解?

假设我的结构看起来像:

    struct Node {
int data; // The data being stored at the node
Node *next; // Pointer to the next node
};



//------------------------------------------------------------------------------
void deleteNthElement (Node * & head, Node * &temp, int random)
{
temp = head;
Node *nodeToRemove;

if (random == 1)
{
nodeToRemove = temp;
head = head->next;
}

else
{
for (int i = 1; i < random - 1; i++)
temp = temp->next;

nodeToRemove = temp->next;
temp->next = temp->next->next;
}

// delete (nodeToRemove); <----- uncommenting this leads to crash,
}//end deleteNthElement()

//------------------------------------------
int main()
{

Node *head = NULL;
Node *temp;
Node *listarray[n[i]];


int n[] = {1000, 5000, 9000, 105000, 400000, 500000, 505000, 800000, 995000, 1000000};

for (int j = 0; j < n[i]; j++)
listarray[j] = new (Node);

//start timer
begin = clock();

//fill it
for (int j = 0; j < n[i]; j++)
{
listarray[j]->data = (rand() % n[i] + 1);
insertNodeInOrder (head, temp, listarray[j]);
}

//delete it
for (int j = 0; j < n[i]; j++)
deleteNthElement (head, temp, (rand() % (n[i] - j) + 1));

//deallocate
for (int j = 0; j < n[i]; j++)
delete listarray[j];

delete *listarray;

//end timer
}

最佳答案

你选错了Node,你想要:

 ...
nodeToRemove = temp;
...

关于c++ - 从链表中释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26405292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com