一个关于c语言链表的问题

img


#include <stdio.h>
#include <stdlib.h>
 static struct node *flag;
typedef struct node
{
    int data;
    struct node *next;
}NODE;
struct node* add( struct node *head,int value);   
void print(NODE *h);

int main( )
{
   NODE *head=NULL;
   int x;
       
   while(1){
      scanf("%d",&x);
      if(x==-1) break;
       head=add(head,x);     
   }
     
   print(flag);   
   
   return 0;
}

void print(struct node *h) 
{
    while(h!=NULL){
        printf("%3d",h->data);
        h=h->next;
    }
}

struct node* add( struct node *head,int value)
{
     static int n=0;
     n++;
       
    struct node *p=head;
   struct node *pr;
    pr = (struct node*)malloc(sizeof(struct node));   
    
    
   
    while(p!=NULL){             
        p = p->next;
        
    }
    if(p!=NULL){             
        pr->next = p->next;  
        p->next = pr;       
    }
   pr->data=value;
   if(n==1)
   {
      flag=pr;
   }
   return head;
}

你没有对链表初始化分配内存空间吧!其他代码也看不到

你这个n是干啥的?它还有print函数为啥传进去flag?你可以先去理解原理,这个代码我觉得有点问题(思维上)