2016-10-23 23 views
0

所以我有一个任务,涉及在C++中创建一个虚构的内存管理器。下面是说明从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

使用正确的工具随时随地解决这样的问题是你的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –

+0

第7行是不必要的......'iterator-> programName =“FREE”;',你已经检查过它是否免费 – amanuel2

+0

我们没有看到'iterator-> programName'的类型。如果它是'char *',并且不起作用,那很正常。 –

回答

0

我正在猜测这里,但做这些假设:
*您链接列表包含您的内存管理器管理的所有内存块
*如果节点代表一个内存块是免费的,然后programName被设置为“免费”
*如果该节点是由程序采取然后programName设置为程序的名称
*您实际上不删除任何节点,只是重新标记为“免费”

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."; 
} 
0

好吧,米只是给你一个通用的版本从链接列表中删除节点。从列表中删除节点时,必须提出三种情况。

  1. 如果列表为空
  2. 如果你想删除的节点是头
  3. 如果节点是其他
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; 
     } 
    } 
    }