首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

动态链表不能打印输入的第一个数解决思路

2012-03-07 
动态链表不能打印输入的第一个数#includestdio.h#includestdlib.htypedefstructNode*Positiontypedef

动态链表不能打印输入的第一个数
#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;
}

热点排行