AKIHIY 2021-11-30 07:33 采纳率: 82.8%
浏览 27
已结题

一个关于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;
}
  • 写回答

2条回答 默认 最新

  • 万小橘 2021-11-30 07:45
    关注

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

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 12月2日
  • 创建了问题 11月30日