为什么我的函数没有打印出双向链表中的第一个节点?
Why isn't my function printing out the first node in the doubly linked list?
我正在编写一个程序来模拟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;
您是否将头部和尾部字段设置为构造函数中的空?如果不是。
相关文章:
- 只有我的"链接列表"中的第一个节点正在打印
- 双向链表 - 无法删除第一个节点
- 链表中头/第一个节点的声明
- 链表.如何删除列表中的第一个节点?
- 链接列表正在抛出异常,而不是打印第一个节点
- 如何删除第一个节点并将其插入链接列表C 的末尾
- 为什么我的函数没有打印出双向链表中的第一个节点?
- 这是在双链表的第一个节点之后插入节点的正确方法吗?
- 返回在函数中创建的 std::list 的第一个节点
- 从链表的第一个节点中删除时出现段错误
- 如何将第一个节点移至链接列表C 中的列表末尾
- 创建第一个节点.js插件
- 在列表末尾插入具有第一个节点的数据的节点
- 访问stl列表的第一个节点
- RapidXML 解析卡在第一个节点C++上
- 在循环双向链表的第一个节点之前/之后插入的算法是什么?
- 如何在 c++ 中删除链表的第一个节点
- 如何删除双链接列表中的第一个节点
- 为什么将链表的第一个节点声明为指针
- 二叉搜索树无法删除第一个节点