I've tried searching for a problem similar to mine, but haven't found much help.
I have a linked list of structs of this type:
struct PCB {
struct PCB *next;
int reg1, reg2;
};
I first create 10 PCB structs linked together in this way:
for(i=20;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = i;
curr->next = head;
head = curr;
}
I then need to create 20 more PCB structs, but their reg1
values need to be generated using rand()
. I'm currently doing that as so:
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr->next = head;
head = curr;
}
However, when inserting these PCB structs into the linked list with random reg1
values, I need to be inserting them in the linked list in order (insertion sort). What is the best way to approach this in just a single-link linked list? Thanks
EDIT: I am now keeping track of the first created struct to be able to loop through the linked list from the beginning:
// create root struct to keep track of beginning of linked list
root = (struct PCB *)malloc(sizeof(struct PCB));
root->next = 0;
root->reg1 = 20;
head = NULL;
// create first 10 structs with reg1 ranging from 20 to 30
for(i=21;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
// link root to current struct if not yet linked
if(root->next == 0){
root->next = curr;
}
curr->reg1 = i;
curr->next = head;
head = curr;
}
Then, when I'm creating the additional 10 PCB structs that need to be insertion sorted:
// create 20 more structs with random number as reg1 value
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
// get root for looping through whole linked list
curr_two = root;
while(curr_two) {
original_next = curr_two->next;
// check values against curr->reg1 to know where to insert
if(curr_two->next->reg1 >= curr->reg1) {
// make curr's 'next' value curr_two's original 'next' value
curr->next = curr_two->next;
// change current item's 'next' value to curr
curr_two->next = curr;
}
else if(!curr_two->next) {
curr->next = NULL;
curr_two->next = curr;
}
// move to next struct in linked list
curr_two = original_next;
}
head = curr;
}
But this immediately crashed my program.