Ho provato a cercare un problema simile al mio, ma non ho trovato molto aiuto.Ordinamento inserzione nella lista collegata in C?
ho una lista concatenata di struct di questo tipo:
struct PCB {
struct PCB *next;
int reg1, reg2;
};
ho creare 10 struct PCB collegati tra loro in questo modo:
for(i=20;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = i;
curr->next = head;
head = curr;
}
Ho quindi bisogno di creare altri 20 struct PCB , ma i loro valori reg1
devono essere generati utilizzando rand()
. Attualmente sto facendo che come in:
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr->next = head;
head = curr;
}
Tuttavia, quando si inseriscono queste le strutture PCB alla lista linkata con casuali reg1
valori, ho bisogno di essere inserendoli nella lista collegata al fine (insertion sort). Qual è il modo migliore per avvicinarsi a questo in un elenco collegato a collegamento singolo? Grazie
EDIT: Ora sto tenendo traccia del primo struct creato per essere in grado di scorrere la lista collegata dall'inizio:
// 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;
}
Poi, quando sto creando le ulteriori 10 struct PCB che deve essere ordinato per l'inserimento:
// 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;
}
Ma questo ha immediatamente fatto crashare il mio programma.
questo ha funzionato correttamente! grazie! – Jakemmarsh
Ma Hey, ho solo copiato il commento da @Joachim! – wildplasser