我已经实现了链接列表代码,但似乎我的代码中存在某个逻辑错误,有人可以帮我解决这个问题吗?
struct Node{
int val;
struct Node *next;
};
void add(struct Node *new_node, struct Node *head){
struct Node *new_n;
if( head == NULL){
head = new_node;
}
else{
new_n = head;
while(new_n){
new_n = new_n->next;
}
new_n = new_node;
}
}
void print(struct Node*n){
while(n != NULL){
fprintf(stderr, "val:%d addr%p \t next%p\n",n->val, n, n->next);
n=n->next;
}
}
void main (){
struct Node *head;
struct Node *node;
int i ;
for( i =1; i< 5; i++){
struct Node *node = malloc(sizeof(*node));
bzero(node,sizeof(*node));
node->val = i;
node->next =NULL;
add(node, head);
}
print(head);
}
此代码不会打印任何值?这段代码有什么问题? [我用过:$ gcc filename.c -o filename.o]
答案 0 :(得分:1)
我看到三个问题:
1)head
永远不会被初始化
使用:
struct Node *head = NULL;
2)对head
函数内add
的更改 更改head
中的main
尝试
void add(struct Node *new_node, struct Node **head){
^^
并在函数中使用*head
并将其称为add(node, &head);
3)新元素未添加到列表中。
尝试:
void add(struct Node *new_node, struct Node **head) {
struct Node *new_n;
if (*head == NULL) {
*head = new_node;
}
else {
new_n = *head;
while (new_n->next) { // Notice - iterate until the next pointer is NULL
new_n = new_n->next;
}
new_n->next = new_node; // Notice
}
}
答案 1 :(得分:0)
执行此操作时,您将返回指向新头节点的指针,因此可以在列表末尾迭代包含新元素的新列表。
struct Node{
int val;
struct Node *next;
};
*Node add(struct Node *new_node, struct Node *head)
{
struct Node *new_n;
if( head == NULL)
{
head = new_node;
}
else
{
new_n = head;
while(new_n)
{
new_n = new_n->next;
}
new_n = new_node;
}
return new_n;
}
void print(struct Node*n){
while(n != NULL){
fprintf(stderr, "val:%d addr%p \t next%p\n",n->val, n, n->next);
n=n->next;
}
}
void main (){
struct Node *head;
struct Node *node;
int i ;
for( i =1; i< 5; i++){
struct Node *node = malloc(sizeof(*node));
bzero(node,sizeof(*node));
node->val = i;
node->next =NULL;
*head = add(node, head);
}
print(head);
}