When a certain if statement is passed i have to remove the head node from my first linked-list "new_queue" and add this to the back of my second linked-list "ready_queue".
When I try this the head gets removed from "new_queue" but it does not get added to the back of "ready_queue", instead it always just replaces the second node in "ready_queue".
I think this is because of the line ready_queue_prev -> next = NULL;
, but if I remove this line the whole linked list will be put at the back of "ready_queue" instead of just the node.
Anyone know how to solve this?
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;
}
}
}
CodePudding user response:
This statement is indeed making the node the second one in the list:
ready_queue -> next = ready_queue_prev;
ready_queue
is the head of the queue, not the tail. You need to first find out where is the tail, and then do that assignment there:
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;
CodePudding user response:
When a certain if statement is passed i have to remove the head node from my first linked-list "new_queue" and add this to the back of my second linked-list "ready_queue".
To add a node to the tail of a linked list you have to find the tail.
First of all actually you need to check whether new_queue
is not equal to NULL
. If it is equal to NULL
then there is nothing to append. The if statement (without any else because it is not required) can look the following way
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;
}