向链表中添加节点



我用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 emptyn");
       newptr->data = data;
       newptr->next = NULL;
       first = newptr;
   }
   else {
       printf("Adding to the existing listn");
       printf("Data in the first node is %d",first->data);
   }

}
void display() {
   struct Node *ptr;
   printf("In the display functionn");
   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;
}

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

下面是新的显示功能:

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

相关内容

  • 没有找到相关文章

最新更新