[英]Delete a specific item from Linked List in 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。 因此,我試圖說說程序名是否等於用戶輸入的程序名,然后將其刪除。 我只是困惑為什么它不起作用
我在這里猜測,但要做出以下假設:
*您的鏈接列表包含由內存管理器管理的所有內存塊
*如果代表一個內存塊的節點是空閑的,則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.";
}
好的,所以我只給您一個通用版本,以從鏈接列表中刪除節點。 從列表中刪除節點時,必須采取三種情況。
- 如果列表為空
- 如果要刪除的節點是head
- 如果節點在其他任何地方
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.