如何在C中实现单向链表

How to implement singly linked list in C

我正在尝试用 C 填充我的链表,但 id 没有说明如何 我想要。我想保留一个指针 "p" 并使用相同的指针继续添加到列表中。但是当我尝试打印时,它只打印了头部的数据!

#include<stdio.h>
#include <stdlib.h>

 typedef struct{
  int data;
  struct node *next;
}node;

int main(){
   node *head = NULL;
   head =  malloc(sizeof(node));
   if(head==NULL){
     printf("ta foirer quelque chose frero!");
     return 1;
   }
   (*head).data=3;
   (*head).next=NULL;

   node *p = NULL;

  p = (node*) head->next;
  p =  malloc(sizeof(node));
  p->data = 5;

  p->next = NULL;
  p= (node *)p->next;

  int i=0;
  while(i<5){
    p =  malloc(sizeof(node));
    i++;
    p->data = i;
    p->next=NULL;
    p= (node *)p->next;
  }


  p = head;

  while(p){
    printf("\n%d",p->data);
    p =(node*) p->next;
  }

  return 0;
}

我得到的是输出

3

我期待得到

3
5
0
1
2
3
4
#include<stdio.h>
#include <stdlib.h>

struct Node {
  int data;
  struct Node *next;
};

typedef struct Node node;

void insert(node* h, int v) {
    node* tmp = h;

    while(tmp->next)
        tmp = tmp->next;
    node* newnode = malloc(sizeof(node));
    newnode->data = v;
    newnode->next = NULL;
    tmp->next = newnode;
}

int main(){
   node *head = NULL;
   head =  malloc(sizeof(node));
   if(head==NULL){
     printf("ta foirer quelque chose frero!");
     return 1;
   }
   head->data=3;
   head->next = NULL;


   node *p = NULL;

  insert(head, 5);
  int i=0;
  while(i<5){
    insert(head, i++);
  }


  p = head;

  while(p){
    printf("%d\n",p->data);
    p = p->next;
  }

  return 0;
}

如果您注意到了,我稍微更改了您的代码布局,使其更简洁。您需要的是遍历找到 之前出现的 节点 以添加新节点 ,在本例中是结束。通常这是包含头部的不同结构中的单独指针,这称为链表的 tail。您根本没有跟踪 where 来真正添加节点。上面的插入函数就是这样做的。