c++ - 我如何添加到链表以进行最佳管理或删除某些内容?

标签 c++ memory-management

我在链表最适合内存管理方面遇到了问题。我创建了链表并添加了第一个元素,但之后没有添加任何其他元素。它基本上避免了我的 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 循环永远不会执行,因为 firstprev 节点将始终为 NULL

你的整体逻辑的意图有点不清楚,但至少这回答了你为什么“它之后没有添加任何其他东西”的问题。

关于c++ - 我如何添加到链表以进行最佳管理或删除某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41112664/

相关文章:

c++ - 调试后 CMD 窗口什么也没有显示

c++ - 如何从 leetcode 中获取 main 函数?

python - 类的实例使用哪些资源?

c++ - 实现内存管理模板类时未解析的外部符号

c++ - 如何检查是否使用 malloc 或 new 分配了内存

c++ - 所有的公共(public)方法都应该对应业务逻辑吗?

c++ - 删除指向数组 C++ 的数组指针时出错

c++ - 模板与类似的非模板函数

c++ - NSObject PerformSelector 问题

c++ - OpenCV 尝试分配 10 艾字节