我已经实现了一个链表代码,但似乎我的代码中存在逻辑错误,谁能帮我解决这个问题?
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%pn",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文件名.c -o 文件名.o]
我看到三个问题:
1(head
从不初始化
用:
struct Node *head = NULL;
2(add
函数内对head
的更改不会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
}
}
执行此操作时,将返回指向新头节点的指针,因此可以迭代包含列表末尾新元素的新列表。
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%pn",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);
}