我在链表最适合内存管理方面遇到了问题。我创建了链表并添加了第一个元素,但之后没有添加任何其他元素。它基本上避免了我的 else 声明。如果有人可以给我一个关于如何做的概念,或者如果我做错了什么,如果你让我知道,那就太好了!
unsigned int MaxMem = 400000000;
struct PCB
{
struct PCB *next;
struct PCB *prev;
int PID;
unsigned int PrSize;
int best;
unsigned int Begin;
unsigned int End;
}*node = NULL, *first = NULL, *node1 = NULL, *node2 = NULL;
class linked
{
public:
void Mem_begin(PCB a)
{
PCB *add = new PCB;
struct PCB *save;
int bestfit = -1;
//add->End = MaxMem;
add->Begin = a.PrSize;
add->next = NULL;
if((first == NULL) && (bestfit1 == -1))
{
bestfit = a.ProcessID;
a.best = bestfit;
add->prev = NULL;
first = add;
cout << first->prev << " - " << first->Begin << " Process " << bestfit << endl;
}
else
{
save = first;
while(save->prev != NULL)
{
bestfit = a.PID;
a.best = bestfit;
save = save->next;
save->next = add;
add->prev = save;
cout << " i did it" << endl;
}
}
}
void display(PCB a) {
node = first;
while(node != NULL)
{
cout << node->prev << " - " << node->Begin << " Process " << a.best << endl;
node = node->next;
}
}
};
int main()
{
PCB test;
linked try;
while(true)
{
cout << "What is the PID?" << endl;
cin >> test.PID;
cout << "How much memory space?" << endl;
cin >> test.PrSize;
try.Mem_begin(test);
}
}
最佳答案
当显示的代码安装链表中的第一个元素时:
add->prev = NULL;
first = add;
第一个节点的prev
指针为NULL
(next
也为NULL),first
指向第一个元素。
当列表不为空时,逻辑如下:
save = first;
while(save->prev != NULL)
而且,由于我们刚刚讨论了初始节点的 prev
指针是 NULL
,所以这匹马在起跑门外就一败涂地。 while
循环永远不会执行,因为 first
的 prev
节点将始终为 NULL
。
你的整体逻辑的意图有点不清楚,但至少这回答了你为什么“它之后没有添加任何其他东西”的问题。
关于c++ - 我如何添加到链表以进行最佳管理或删除某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41112664/