我正在尝试编写一段将元素添加到列表中的代码。
cqlsh:test> insert into address_table (name, addresses) values ('Caroline', null);
cqlsh:test> update address_table set addresses = null where name = 'Dexter' ;
cqlsh:test> select * from address_table;
name | addresses
----------+-----------
Caroline | null
Alice | null
(2 rows)
但是,当我尝试打印列表时,没有任何输出。因此,即使我输入了1 2 3 4..etc,打印功能也不会输出任何东西
typedef struct things {
int value;
struct things *next;
} something;
int main()
{
int input = 0;
something *head = NULL;
something *current = NULL;
current = head; //current points to head address
while(input != -1)
{
scanf("%d", &input);
while(current != NULL) //loop until current node returns NULL
{
current = current->next; //go to next node
}
current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
current->value = input;
current->next = NULL; //next points to NULL
}
current=head; //current points back to head
while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
return 0;
}
我期望输出类似while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
。我刚刚开始学习链接列表,因此请多多指教。
答案 0 :(得分:3)
您在任何时候都不会更新head
的值。或将列表中的最后一个节点指向新创建的节点。
检查是否首先设置了head
,如果没有,请填充它。否则,找到列表的最后一个节点,并将新节点添加为该节点的“下一个”节点,如下所示。
if(head == NULL)
{
head = malloc(sizeof(something));
head->value = input;
head->next = NULL; //next points to NULL
}
else
{
current = head;
while(current->next != NULL) //loop until current node returns NULL
{
current = current->next; //go to next node
}
current->next = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
current->next->value = input;
current->next->next = NULL; //next points to NULL
}
答案 1 :(得分:1)
您当前的方法不适用于单个指针。
在current
分配内存的地方不会将节点插入列表。
只需将current
用作指针,如下所示,您的方法就可以使用。
int input = 0;
something *head = NULL;
something **current = NULL;
current = &head; //current points to head address
while(input != -1)
{
scanf("%d", &input);
while(*current != NULL) //loop until current node returns NULL
{
current = &(*current)->next; //go to next node
}
*current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
(*current)->value = input;
(*current)->next = NULL; //next points to NULL
}
current=&head; //current points back to head
while(*current != NULL)
{
printf("%d -> ", (*current)->value);
current = &(*current)->next;
}
puts("NULL");