好吧,我有一个代码,按字母顺序在列表中插入一个新的结构,但我有一点问题。我只是可以让它工作有一个功能,当我打电话给我做头=插入(frota *头,字符名称)。代码是暂时的
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(&amp; head,name)。任何帮助将是欣赏。当我运行代码时,它出现分段错误并且不是内存错误 PS:代码完全不是我的责任,在网上找到了一些......
感恩
答案 0 :(得分:0)
首先:
更改
int* prevtemp;
是
struct robot * prevtemp;
(nexttemp
相同)
全部改变
head
到
(*head)
全部改变
frota
到
struct robot