所以我有一个任务涉及在C ++中创建一个虚构的内存管理器。以下是说明
编写一个模拟操作系统分配职责的C ++程序 记忆到某些程序。这将是一个非常简单的基于页面的内存视图 管理。在启动时,您的程序将有大约32页连续,未使用 记忆。每页的长度为4 KB
我的问题是删除特定的"程序"来自链表。这是我目前的DestroyProgram方法
void DestroyProgram(string proName) { //Deletes
Node* iterator = head;
while (iterator != NULL) {
if (iterator->programName == "FREE") {
int count = 0;
while (iterator != NULL && iterator->programName == "FREE") {
iterator->programName = "FREE";
iterator = iterator->nextProgram;
}
return;
count++;
}
else {
iterator = iterator->nextProgram;
}
}
cout << iterator->programName << " is not there.";
}
如果未使用内存,则标记为FREE。因此,我试图说出程序名是否等于用户输入的程序名称,然后将其删除。我很困惑为什么它不起作用
答案 0 :(得分:0)
我在这里猜测,但做出这些假设:
*您的链接列表包含由内存管理器管理的所有内存块
*如果表示存储块的节点是空闲的,则programName设置为“FREE”
*如果节点由程序占用,则programName设置为程序名称
*您实际上并没有删除任何节点,只是将它们重新标记为“FREE”
void DestroyProgram(string proName) { //Deletes
Node* iterator = head;
while (iterator != NULL) {
if (iterator->programName == proName) {
int count = 0;
while (iterator != NULL && iterator->programName == proName) {
iterator->programName = "FREE";
iterator = iterator->nextProgram;
}
// If you return here, you're assuming that programs always have memory allocated in consecutive blocks
// If they request memory more than once, the memory blocks may not be together
// In that case, you have to keep searching through to the end of the list
return;
count++;
}
else {
iterator = iterator->nextProgram;
}
}
cout << proName << " is not there.";
}
答案 1 :(得分:0)
好的,我只是给你一个通用版本来从链表中删除一个节点。从列表中删除节点时必须提出三种情况。
- 如果列表为空
- 如果您要删除的节点是
- 如果节点在其他任何地方
醇>
void DestroProgram(string proName) //Deletes
{
Node *iterator = head;
if(head == NULL)
{
cout << "List is empty" << endl;
}
else if(iterator->programName == proName)
{
head = head->nextProgram //point to your new head
delete iterator; //delete your old head
}
else
{
Node *previousNode = head;
while(head != NULL)
{
if(iterator->programName == proName)
{
previousNode->next = iterator->next //make the new connection between nodes
delete iterator
}
previousNode = iterator; //sets previousNode one node behind iterator
iterator = iterator->nextProgram;
}
}
}