我正在尝试将指针传递给main中链接列表的地址,将其传递给函数以向其分配内存并遍历到下一个节点,同时保持下一个节点的位置而不破坏头节点 .
typedef struct {
int data;
struct node_list *next;
}node_list;
typedef struct {
struct node_list *head;
}list;
void insert_list(node_list **c, int num);
void main()
{
int num;
list *list_odd = (list*)calloc(1, sizeof(list));
node_list *c = &list_odd->head;
while (num != -1)
{
if (num % 2)
insert_list(c, num);
}
}
void insert_list(node_list **c, int num)
{
if (*c == NULL)
{
*c = (node_list*)malloc(sizeof(node_list)); // it allocates the memory in the right place.
(*c)->data = num;
(*c) = (*c)->next; // but this step breaks the starting list pointer
}
else
{
(*c)->next = (node_list*)malloc(sizeof(node_list));
(*c)->data = num;
(*c) = (*c)->next;
}
}
编辑:我可能没有解释自己,澄清:如果我的列表指向链表的开头,我分配内存然后做(* c)=(* c) - >接下来,我的头不再指向乞讨 . 我想要实现的是拥有列表的开头并保存下一个节点的位置 .
2 回答
我想建议一个双面的单链表 .
这是一个示范计划 .
如果要输入这个数字序列
然后输出将是
将新节点添加到列表末尾的复杂性是O(1) .
我不完全确定你要做什么,所以我做了一个等效的程序 . 如果您发现这种添加到列表的方式太慢,则需要将程序更改为保留{head,tail}对或将项添加到列表的前面 . 从你的文字听起来你正试图保持头部相同 - 所以{head,tail}对可能是最好的 .