How to implement a linked list in C?

后端 未结 14 854
予麋鹿
予麋鹿 2020-12-06 02:49

I am creating a linked list as in the previous question I asked. I have found that the best way to develop the linked list is to have the head and tail in another structure.

14条回答
  •  执念已碎
    2020-12-06 03:24

    #include 
    struct node
     {
      int data;
      struct node* next;
     };
    
    int main()
    {
    
    //create pointer node for every new element
    
    struct node* head = NULL;
    struct node* second = NULL;
    struct node* third = NULL;
    
    //initialize every new pointer with same structure memory
    
    head = malloc(sizeof(struct node));
    second = malloc(sizeof(struct node));
    third = malloc(sizeof(struct node));
    
    head->data = 18;
    head->next = second;
    
    second->data = 20;
    second->next = third;
    
    
    third->data = 31;
    third->next = NULL;
    
    //print the linked list just increment by address 
    
      for (int i = 0; i < 3; ++i)
        {
          printf("%d\n",head->data++);
          return 0;
        }
     }
    

    This is a simple way to understand how does pointer work with the pointer. Here you need to just create pointer increment with new node so we can make it as an automatic.

提交回复
热议问题