为什么我的函数没有打印出双向链表中的第一个节点?

Why isn't my function printing out the first node in the doubly linked list?

本文关键字:第一个 节点 双向链表 函数 我的 打印 为什么      更新时间:2023-10-16

我正在编写一个程序来模拟CPU调度程序。因此,我正在实施一个双重链接列表,以用作现成的队列。每当添加新过程时,都会创建一个过程控制块(PCB)并添加到"就绪队列"中。每个PCB都具有独特的PID。因此,每当添加新的PCB时,我都会将PID递增。

pid += 1;
currentDevices[0].enqueuePCB(pid);
 //currentDevices[0] represents the ready queue. There are other queues as well

这是我的enqueuepcb函数:

void device::enqueuePCB(int num)
{
    pcb* newPCB = new pcb();
    newPCB -> pid = num;
    newPCB -> next = NULL;
    newPCB -> prev = NULL;
    if (head == NULL)
    {
        head = tail = newPCB;
        queueLength += 1;
    }
    else
    {
        pcb* temp = tail;
        newPCB -> next = tail;
        temp -> prev = newPCB;
        tail = newPCB;
        queueLength += 1;
    }
}

和我的打印功能

void device::snapReadyQueue()
{
    pcb* temp = head;
    cout << "PID: ";
    while (temp != NULL)
    {
        cout << temp -> pid << " ";
        temp = temp -> prev;
    }
    cout << endl;
}

当我测试程序,仅添加一个PCB并打印时会导致空白" PID:"。但是,一旦我开始添加更多的PCB和打印,我实际上可以检索其他PCB的PID。例如,第一个和打印后添加2个PCB会让我

pid:2 3

1丢失,我不明白为什么。我浏览了我的否则声明,以寻找对象,这似乎很有意义。我还尝试使用单独的链接列表,但它不起作用。

更新经过一些测试后,我意识到这可能与我在初始化队列之前使用的IF-ELSE语句有关。

 if (processCount == 0)
    {
        cout << "Currently no processes in the ready queue.nAvailable commands: A: ";
        cin >> call;
        if (call == "A")
        {
            pid = 1;
            currentDevices[0].enqueuePCB(pid);
            processCount += 1;
            run();
        } 
    }
else
    {
        cout << "Please enter call: ";
        cin >> call;
        if (call == "A")
        {
            pid += 1;
            currentDevices[0].enqueuePCB(pid);
            processCount += 1;
            run();
        }

我第一次出现时尝试仅打印头部,并且程序崩溃了。但是,当我添加第二个PCB时,头指向PID 2。

我认为将元素添加到列表的代码是错误的,您说:

    pcb* temp = tail;
    newPCB -> next = tail;
    temp -> prev = newPCB;
    tail = newPCB;
    queueLength += 1;

假设尾巴是指向列表的最后一个元素的指针,我们可以跟踪这里发生的事情。让我们现在忘记temp,您告诉newPCB它的下一个元素是尾巴(当前的最后一个元素)。接下来,您告诉tail它的前身是newPCB,然后将newPCB尾巴尾巴。因此,尾巴是newPCB,其先前的元素是NULL,但它的下一个元素是以前的tail。我认为您的意思是:

    tail -> next = newPCB;
    newPCB -> prev = tail;
    tail = newPCB;

您是否将头部和尾部字段设置为构造函数中的空?如果不是。