添加一个节点到链表

问题描述:

我已经写了我的第一个数据结构代码在C中,我很困惑我做错了什么。我只是试图将节点添加到链接列表的前面或链接到一个空链接列表,并在最后打印列表并导致分段错误。添加一个节点到链表

#include<stdio.h> 
#include<stddef.h> 
#include<cstdlib> 

/* Node representing each node of the linked list */ 
struct Node { 
    int data; 
    struct Node *next; 
}; 

/* Fist node is always null as there are no nodes in the linked list to begin  with */ 
struct Node *first = NULL; 


void add_node(int data) { 
    struct Node *newptr = (Node *)malloc(sizeof(Node)); 
    // Check if the list is empty 
    if (first == NULL){ 
     printf("The list is empty\n"); 
     newptr->data = data; 
     newptr->next = NULL; 
     first = newptr; 
    } 
    else { 
     printf("Adding to the existing list\n"); 
     printf("Data in the first node is %d",first->data); 
    } 


} 

void display() { 
    struct Node *ptr; 
    printf("In the display function\n"); 
    ptr = first; 
    do { 
     printf("Printing the data in the node %d",ptr->data); 
     ptr= ptr->next; 
    }while(ptr->next != NULL); 

} 

int main() { 
    /* 
    * Just try and add one node 
    */ 
    int y = 100; 
    printf("Adding a node \n"); 
    add_node(y); 
    display(); 
    return 1; 

} 
+0

不,我仍然不认为我想通了,对我来说,一切看起来不错。 –

我搞砸了显示功能,我改变了一下有正确的输出。

以下是新的显示功能:

void display(struct Node *first) { 
    struct Node *ptr; 
    printf("In the display function\n"); 
    ptr = first; 
    do { 
     printf("Printing the data in the node %d",ptr->data); 
     ptr= ptr->next; 
    }while(ptr != NULL); 

}