>我的程序显示列表为空。我想我在将节点重新链接到头部时犯了错误。帮我弄清楚。
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++;
}
}
您有两个条件:
- 在链表中查找要插入的位置
- 不会从链表末尾掉下来
而且,当然,你必须分配给*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;
}
您正在使用head
来遍历链表,如果索引与距离匹配,则更新headref
。
问题*headRef = head
在while..if
if(index == 0)
将temp1
分配给*headref
即 *headref=temp1