Próbowałem już szukać problemu podobnego do mojego, ale nie znalazłem zbytniej pomocy.Sortowanie według wpisu na połączonej liście w C?
Mam połączonej listy elemencie tego typu:
struct PCB {
struct PCB *next;
int reg1, reg2;
};
ja najpierw utworzyć 10 konstrukcjom PCB połączone ze sobą w ten sposób:
for(i=20;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = i;
curr->next = head;
head = curr;
}
Następnie należy utworzyć 20 więcej konstrukcjom PCB , ale ich wartości muszą być wygenerowane przy użyciu rand()
. Jestem aktualnie robi, że jak tak:
for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr->next = head;
head = curr;
}
Jednak podczas wstawiania tych konstrukcjom PCB do połączonej listy z losowymi reg1
wartości, muszę być wkładając je w połączonej listy w kolejności (Sortowanie przez wstawianie). Jaki jest najlepszy sposób podejścia do tej kwestii na liście połączonej tylko jednym łączem? Dzięki
EDIT: Jestem teraz śledzenie pierwszej utworzonej struktury, aby móc pętli połączonej listy od początku:
// 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;
}
Potem, kiedy tworzę dodatkowe 10 konstrukcjom PCB które trzeba wstawić posortowane:
// 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;
}
Ale to natychmiast rozbił mój program.
ten działał poprawnie! Dziękuję Ci! – Jakemmarsh
Ale hej, skopiowałem tylko komentarz z @ Joachim! – wildplasser