我的程序显示列表为空。我认为我在将节点重新连接到头部时犯了错误。帮帮我搞清楚。
void insert(struct node** headRef, int index, int Data)
{
int i, distanceFromHead = 1;
struct node* head = *headRef;
struct node* temp1 = (struct node*)malloc(sizeof(struct node)); //node to be inserted.
temp1->data = Data;
if(index == 0)
{
temp1->next = head;
head = temp1;
return;
}
while(head != NULL)
{
if(distanceFromHead == index)
{
temp1->next = head->next;
head->next = temp1;
*headRef = head;
return;
}
head = head->next;
distanceFromHead++;
}
}
答案 0 :(得分:0)
您正在使用head
来遍历链接列表,如果索引与距离匹配,则更新headref
。
*headRef = head
while..if
并if(index == 0)
将temp1
分配给*headref
,即*headref=temp1
答案 1 :(得分:0)
你有两个条件:
当然,您必须分配给*headRef
,而不是某些本地指针变量。在你完全确定你真的需要记忆之前,你不应该调用malloc。
您可以在一个循环中组合这两个条件:
void insert1(struct node **headRef, int index, int Data)
{
struct node *temp1;
int distanceFromHead = 0;
for( ; *head; head = &(*head)->next) {
if(distanceFromHead == index) break;
distanceFromHead++;
}
if (distanceFromHead != index) return; // index not found: list too short
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
}
你不需要distanceFromHeadvarable;你也可以减少索引:
void insert2(struct node **headRef, int index, int Data)
{
struct node *temp1;
for( ; *head; head = &(*head)->next) {
if(!index) break;
index--;
}
if (index) return; // index not found: list too short
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
}
现在,循环后重复index!=0
的测试。这可以通过在循环内移动插入并在之后跳出来避免:
void insert3(struct node **headRef, int index, int Data)
{
for( ; *head; head = &(*head)->next) {
struct node *temp1;
if(index--) continue;
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
break; // or : return;
}
return;
}