动态链表不能打印输入的第一个数
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *Position;
typedef Position List;
Position CreatList(void);
void PrintList(List Head);
struct Node
{
int Element;
Position Next;
};
void main()
{
List head;
head=CreatList();
PrintList(head);
}
Position CreatList(void)
{
List Head;
Position P,Tmp;
int C;
int N=0;
P=Tmp=(Position)malloc(sizeof(struct Node));
scanf( "%d ",&P-> Element);
Head=NULL;
while((C=getchar())!= '\n ')
{
N=N+1;
if(N==1)
Head=P;
else
Tmp=(Position)malloc(sizeof(struct Node));
scanf( "%d ",&Tmp-> Element);
P-> Next=Tmp;
P=Tmp;
}
P-> Next=NULL;
return Head;
}
void PrintList(List Head)
{
Position P;
P=Head;
if(Head!=NULL)
do
{printf( "%-3d ",P-> Element);
P=P-> Next;
}while(P!=NULL);
}
[解决办法]
Head=NULL;
while((C=getchar())!= '\n ')
{
N=N+1; // 为什么要用N, 在循环外给Head赋值是不是会更好呢? : )
if(N==1)
Head=P;
else
Tmp=(Position)malloc(sizeof(struct Node));
scanf( "%d ",&Tmp-> Element);
P-> Next=Tmp;
P=Tmp;
}
-----------------------------------------
改为:
Head = P;
while ((c = getchar()) != '\n ')
{
Tmp=(Position)malloc(sizeof(struct Node));
scanf( "%d ",&Tmp-> Element);
P-> Next=Tmp;
P=Tmp;
}