【发布时间】:2016-01-03 18:34:12
【问题描述】:
我正在尝试为简单的链表编写一些函数。这个应该在列表之间的某处添加一个节点。用户放入列表的头部,此时应该保存的数据“c”和应该保存的索引“x”。但它基本上什么都不做,我不知道为什么。也许有人能看出错误。
第一个 if 语句只是检查索引是否是列表的一部分。
DoubleNode *insert(DoubleNode *head, double c, int x)
{
int i;
DoubleNode *cursor, *tmp, *newl;
cursor = head->next;
newl = head;
if (x > Index(newl) || x < 1)
{
printf("FAIL\n");
return NULL;
}
else {
while (cursor != NULL)
{
newl->next = cursor;
cursor = cursor->next;
if (i == x)
{
tmp = malloc(sizeof(DoubleNode));
if (tmp == NULL)
{
printf("Fail");
return NULL;
}
tmp->data = c;
tmp->next = cursor;
cursor = tmp;
}
i++;
}
}
return newl;
}
【问题讨论】:
-
我卡在
while (cursor != NULL)。cursor对空列表有什么价值? -
Index(newl)是做什么的? -
函数 Index(newl) 是更大程序的一部分,它只计算列表中有多少节点。所以索引不能大于列表中的元素。
-
标签: c linked-list singly-linked-list