C中的链表打印额外的零
我试图学习使用指针,尤其是列表,但我有一个问题。 我的链表有点问题。 我不明白为什么它会在列表的顶部多打印一个零。 这是代码。 多谢各位C中的链表打印额外的零,c,list,C,List,我试图学习使用指针,尤其是列表,但我有一个问题。 我的链表有点问题。 我不明白为什么它会在列表的顶部多打印一个零。 这是代码。 多谢各位 #include <stdio.h> #include <stdlib.h> struct Node{ int val; struct Node *next; }; void insert(struct Node *head, int val); void print(struct Node *head); in
#include <stdio.h>
#include <stdlib.h>
struct Node{
int val;
struct Node *next;
};
void insert(struct Node *head, int val);
void print(struct Node *head);
int main(){
struct Node *head = NULL;
head = malloc(sizeof(struct Node));
insert(head, 5);
print(head);
return 0;
}
void insert(struct Node *head, int val){
if(head == NULL){
printf("Error");
return;
}
struct Node* tmp = malloc(sizeof(struct Node));
tmp->val = val;
tmp->next = NULL;
while(head->next != NULL){
head = head->next;
}
head->next = tmp;
}
void print(struct Node *head){
while(head != NULL){
printf("%d\n", head->val);
head = head->next;
}
}
在代码中,您总是设置tmp->val,但从未设置head->val
在打印循环中,对于第一次迭代,您正在读取一个单位化的值。根据您的数据结构,您应该开始从第二个节点读取值。您的列表如下所示: +-----------+ +------------------------+ +-------------------------+ | head node | --> | first node in the list | --> | second node in the list | --> ... +-----------+ +------------------------+ +-------------------------+
void insert(struct Node **head)
{
struct Node* tmp = malloc(sizeof(struct Node));
tmp->val = val;
tmp->next = NULL;
if (*head == NULL)
{
// List is empty, add first node in the list
*head = tmp;
else
{
// Non-empty list, add at tail
struct Node *iter = *head;
while (iter->next != NULL)
iter = iter->next;
iter->next = tmp;
}
}
另一种可能的解决方案是不使用虚拟头部节点,而是让头部节点成为列表中的第一个节点。这需要更改insert函数并跳过head节点的分配
最大的更改是将insert函数更改为通过使用指向头节点指针的指针模拟的引用接收头节点
也许是这样的:
+-----------+ +------------------------+ +-------------------------+
| head node | --> | first node in the list | --> | second node in the list | --> ...
+-----------+ +------------------------+ +-------------------------+
void insert(struct Node **head)
{
struct Node* tmp = malloc(sizeof(struct Node));
tmp->val = val;
tmp->next = NULL;
if (*head == NULL)
{
// List is empty, add first node in the list
*head = tmp;
else
{
// Non-empty list, add at tail
struct Node *iter = *head;
while (iter->next != NULL)
iter = iter->next;
iter->next = tmp;
}
}
打电话
struct Node *head = NULL;
insert(&head, 5);