I tried to find a problem similar to mine, but did not find much help.
I have a linked list of structures of this type:
struct PCB {
struct PCB *next;
int reg1, reg2;
};
First I create 10 PCB structures interconnected as follows:
for(i=20;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = i;
curr->next = head;
head = curr;
}
Then I need to create another 20 PCB structures, but their values reg1should be generated using rand(). I am doing it like this:
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr->next = head;
head = curr;
}
However, when pasting these PCB structures into a linked list with random values, reg1I need to insert them into the linked list in order (insertion sort). What is the best way to approach this in just one list of links? Thanks
EDIT: Now I am tracking the first structure created to be able to scroll through the linked list from the very beginning:
root = (struct PCB *)malloc(sizeof(struct PCB));
root->next = 0;
root->reg1 = 20;
head = NULL;
for(i=21;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
if(root->next == 0){
root->next = curr;
}
curr->reg1 = i;
curr->next = head;
head = curr;
}
, 10 PCB, :
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr_two = root;
while(curr_two) {
original_next = curr_two->next;
if(curr_two->next->reg1 >= curr->reg1) {
curr->next = curr_two->next;
curr_two->next = curr;
}
else if(!curr_two->next) {
curr->next = NULL;
curr_two->next = curr;
}
curr_two = original_next;
}
head = curr;
}
.