【发布时间】:2016-03-26 08:28:21
【问题描述】:
我试图将我在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)->next,我的头不再指向乞讨。我想要实现的是拥有列表的开头并保存下一个节点的位置。
【问题讨论】:
-
有问题吗?如果是这样,它是什么?当你调试你的调试器时你发现了什么?
-
@Dannz 编译将发出一条消息,因为使用了类型不兼容的 node_list 和 struct node_list 指针。
-
如果我的列表指向链表的开头,而我为它分配内存然后执行 (*c) = (*c)->next,我的头不再指向乞讨。我想要实现的是拥有列表的开头并保存下一个节点的位置。
-
@Dannz 另外我认为函数的第一个参数应该是列表。
-
@VladfromMoscow 我可以发送列表并遍历到列表末尾,但这将是 O(n),我认为有可能使 O(1)。
标签: c pointers struct linked-list