當某個 if 陳述句通過時,我必須從我的第一個鏈表“new_queue”中洗掉頭節點,并將其添加到我的第二個鏈表“ready_queue”的后面。
當我嘗試這個時,頭部會從“new_queue”中移除,但它不會添加到“ready_queue”的后面,而是總是替換“ready_queue”中的第二個節點。
我認為這是因為 line ready_queue_prev -> next = NULL;,但如果我洗掉這一行,整個鏈表將被放在“ready_queue”的后面,而不僅僅是節點。
有誰知道如何解決這個問題?
typedef struct ST_PCB {
int arrival_time;
char name[9];
int duration;
struct ST_PCB * next;
} T_PCB;
int main(void){
// serial list of newly arrived tasks
T_PCB * new_queue = NULL;
// circular list of active tasks
T_PCB * ready_queue = NULL;
// extra state needed to switch tasks
// from new_queue to ready_queue when they're started
T_PCB * ready_queue_prev = NULL;
//this constructs the linked-list and sorts it by arrival time
new_queue = read_tasks();
new_queue = sort_tasks_on_arrival(new_queue);
if(something happends...){
if(ready_queue != NULL){
ready_queue_prev = new_queue;
new_queue = new_queue->next;
ready_queue -> next = ready_queue_prev;
ready_queue_prev -> next = NULL;
}
else{
ready_queue = new_queue;
new_queue = new_queue->next;
ready_queue->next = NULL;
}
}
}
uj5u.com熱心網友回復:
當某個 if 陳述句通過時,我必須從我的第一個鏈表“new_queue”中洗掉頭節點,并將其添加到我的第二個鏈表“ready_queue”的后面。
要將節點添加到鏈表的尾部,您必須找到尾部。
首先實際上你需要檢查是否new_queue不等于NULL。如果它等于,NULL則沒有什么可附加的。if 陳述句(沒有任何其他,因為它不是必需的)可以如下所示
if ( new_queue != NULL)
{
T_PCB *tmp = new_queue;
new_queue = new_queue->next;
tmp->next = NULL;
T_PCB **current = &ready_queue;
while ( *current != NULL ) current = &( *current )->next;
*current = tmp;
}
uj5u.com熱心網友回復:
該陳述句確實使該節點成為串列中的第二個:
ready_queue -> next = ready_queue_prev;
ready_queue是佇列的頭部,而不是尾部。你需要先找出尾巴在哪里,然后在那里做那個作業:
T_PCB * tail = ready_queue;
while (tail->next != NULL) {
tail = tail->next;
}
// We found the tail. Now make the assignment to `next`:
tail->next = ready_queue_prev;
// And now continue with what you had:
ready_queue_prev->next = NULL;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/474096.html
上一篇:`offsetof(structDerived,super.x)==offsetof(structBase,x)`在C中是否成立?
