大家好?请教单链表有关问题

大家好?请问单链表问题。

#include <stdlib.h> /*包含malloc( ) 的头文件*/
#include <stdio.h>

struct node /*链表节点的结构*/
{
int num;
struct node *next;
} ;



struct node * creat(struct node *head);
void print(struct node * head);

int 
main ()
{
  struct node *head; /*定义头指针*/
  head=NULL;/*建一个空表*/
  head=creat(head);/*创建单链表*/
  print(head);/*打印单链表*/
  return 0;
}
/******************************************/ 


struct node * creat(struct node *head)/*数函返回的是与节点相同类型的指针*/
{
int i=1;
struct node*p1,*p2;

p1=p2=(struct node*)malloc(sizeof(struct node)); /*申请新节点*/
scanf("%d",&p1->num); /*输入节点的值*/
p1->next=NULL; /*将新节点的指针置为空*/
while(p1->num>0) /*输入节点的数值大于0*/
{
if(head==NULL)
head=p1; /*空表,接入表头*/
else
p2->next=p1; /*非空表,接到表尾*/

p2=p1;
p1=(struct node*)malloc(sizeof(struct node)); /*请申下一个新节点*/
scanf("%d",&p1->num); /*输入节点的值*/
i++;

}
printf("total : %d",i);
return head; /*返回链表的头指针*/
}
/*******************************************/
void print(struct node*head)/*输出以head为头的链表各节点的值*/
{
struct node *temp;
temp=head; /*取得链表的头指针*/
while(temp!=NULL) /*只要是非空表*/
{
printf("%6d\n",temp->num); /*输出链表节点的值*/
temp=temp->next; /*跟踪链表增长*/
}



------解决方案--------------------
问题在哪里?
------解决方案--------------------
楼主要养成malloc后就memset的好习惯哦
问题就在这里,请看// jernymy处标记
同时i的值计数错误,多了1

C/C++ code

#include <stdlib.h> /*包含malloc( ) 的头文件*/
#include <stdio.h>
#include <string.h> // jernymy
// ......


struct node * creat(struct node *head)/*数函返回的是与节点相同类型的指针*/
{
    int i=0; // jernymy
    struct node*p1,*p2;
    
    p1=p2=(struct node*)malloc(sizeof(struct node)); /*申请新节点*/
    memset(p1, 0, sizeof(struct node)); // jernymy
    scanf("%d",&p1->num); /*输入节点的值*/
    p1->next=NULL; /*将新节点的指针置为空*/
    while(p1->num>0) /*输入节点的数值大于0*/
    {
        if(head==NULL)
            head=p1; /*空表,接入表头*/
        else
            p2->next=p1; /*非空表,接到表尾*/
        
        p2=p1;
        p1=(struct node*)malloc(sizeof(struct node)); /*请申下一个新节点*/
        memset(p1, 0, sizeof(struct node)); // jernymy
        scanf("%d",&p1->num); /*输入节点的值*/
        i++;
        
    }
    printf("total : %d",i);
    return head; /*返回链表的头指针*/
}