gpt4 book ai didi

c - C中链表的插入排序?

转载 作者:太空狗 更新时间:2023-10-29 14:56:27 25 4
gpt4 key购买 nike

我曾尝试搜索与我的问题类似的问题,但没有找到太多帮助。

我有一个这种类型的结构链表:

struct PCB {
struct PCB *next;
int reg1, reg2;
};

我首先创建了 10 个以这种方式链接在一起的 PCB 结构:

for(i=20;i<=30;i++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = i;
curr->next = head;
head = curr;
}

然后我需要再创建 20 个 PCB 结构,但它们的 reg1 值需要使用 rand() 生成。我目前正在这样做:

for (j = 0;j<20;j++) {
curr = (struct PCB *)malloc(sizeof(struct PCB));
curr->reg1 = rand()%100;
curr->next = head;
head = curr;
}

但是,当将这些 PCB 结构插入具有随机 reg1 值的链表时,我需要按顺序将它们插入链表(插入排序)。仅在单链接链表中处理此问题的最佳方法是什么?谢谢

编辑:我现在正在跟踪第一个创建的结构,以便能够从头开始循环遍历链表:

// 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;
}

然后,当我创建另外 10 个需要插入排序的 PCB 结构时:

// 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;
}

但这立即让我的程序崩溃了。

最佳答案

“最佳”方法可能是为插入实现一个新函数。此函数将遍历列表,直到找到其 next nodes 值小于或等于要插入的节点的节点,然后将新节点放在 next 之前节点。


这个函数怎么样:

void insert(struct PCB **head, const int reg1, const int reg2)
{
struct PCB *node = malloc(sizeof(struct PCB));
node->reg1 = reg1;
node->reg2 = reg2;
node->next = NULL;

if (*head == NULL)
{
/* Special case, list is empty */
*head = node;
}
else if (reg1 < (*head)->reg1)
{
/* Special case, new node is less than the current head */
node->next = *head;
*head = node;
}
else
{
struct PCB *current = *head;

/* Find the insertion point */
while (current->next != NULL && reg1 < current->next->reg1)
current = current->next;

/* Insert after `current` */
node->next = current->next;
current->next = node;
}
}

你可以这样调用它:

insert(&root, rand() % 100, 0);

关于c - C中链表的插入排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15960040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com