gpt4 book ai didi

c - 如何按字母顺序在列表中插入结构体

转载 作者:行者123 更新时间:2023-11-30 19:42:57 24 4
gpt4 key购买 nike

嗯,我有一个代码可以按字母顺序在列表中插入一个新结构,但我遇到了一个小问题。我只需让它工作有一个函数,当我调用时,我使 head = Insert(frota* head, char name)。代码如下

typedef struct robot {
int bateria;
char nome[3];
int pos_x;
int pos_y;
int target_x;
int target_y;
int limpos;
int percorridos;
struct robot * next;
}frota;

frota* Insert(frota* head, char name){
frota* temp = (frota*)malloc(sizeof(frota));
if(temp == NULL){
printf("Unable to allocate memory for new node\n");
exit(-1);
}
temp->nome[0] = 'R';
temp->nome[1] = name;
int* prevtemp = head;
int* nexttemp = head;
if(head != NULL)
{
// Corner Case: First on the list
if(temp->nome[1] <= prevtemp->nome[1])
{
head = temp;
temp->next = prevtemp;
}
else
{
// CASE: Somewhere between the first and the list
while(nexttemp->next != NULL)
{
nexttemp = nexttemp->next;
if(temp->nome[1] >= prevtemp->nome[1] && temp->nome[1] <= nexttemp->nome[1])
{
prevtemp->next = temp;
temp->next = nexttemp;
break;
}
prevtemp = prevtemp->next;
}

// Corner Case: end of list
if(nexttemp->next == NULL)
{
nexttemp->next = temp;
}
}
}
else
{
// Corner Case: We had an empty list
head = temp;
}
}

我的问题是如何使代码正常工作并直接更改值头的值,从而使该函数成为一个过程。我尝试过的代码是这样的:

void Insert(frota* head, char name){
frota* temp = (frota*)malloc(sizeof(frota));
if(temp == NULL){
printf("Unable to allocate memory for new node\n");
exit(-1);
}
temp->nome[0] = 'R';
temp->nome[1] = name;
int* prevtemp = *head;
int* nexttemp = *head;
if(*head != NULL)
{
// Corner Case: First on the list
if(temp->nome[1] <= prevtemp->nome[1])
{
*head = temp;
temp->next = prevtemp;
}
else
{
// CASE: Somewhere between the first and the list
while(nexttemp->next != NULL)
{
nexttemp = nexttemp->next;
if(temp->nome[1] >= prevtemp->nome[1] && temp->nome[1] <= nexttemp->nome[1])
{
prevtemp->next = temp;
temp->next = nexttemp;
break;
}
prevtemp = prevtemp->next;
}

// Corner Case: end of list
if(nexttemp->next == NULL)
{
nexttemp->next = temp;
}
}
}
else
{
// Corner Case: We had an empty list
*head = temp;
(*head)->next = NULL;
}
}

这样我将过程称为 Insert(&head,name)。任何帮助将不胜感激。当我运行代码时,它出现段错误,而不是内存错误PS:该代码不完全由我负责,在网上找到了一些部分......

感恩

最佳答案

对于初学者:

改变

int* prevtemp;

成为

struct robot * prevtemp;

(与 nexttemp 相同)

<小时/>

全部更改

head

(*head)
<小时/>

全部更改

frota

struct robot

关于c - 如何按字母顺序在列表中插入结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288103/

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