首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

帮忙看看链表!解决思路

2012-02-28 
帮忙看看链表!#include stdio.h#include malloc.h#defineLENsizeof(structstudent)structstudent{intn

帮忙看看链表!
#include <stdio.h>
#include <malloc.h>
#define   LEN   sizeof(struct   student)
struct   student{
int   number;
int   score[3];

struct   student   *next;
};
struct   student   *creat(struct   student   *head)
{
struct   student   *p1,*p2;
printf( "qingshuruxueshengshuju:\n ");
p1=(struct   student*)malloc(sizeof(LEN));
if   (p1==NULL)printf( "memory   error:\n ");
scanf( "%d%d%d%d ",&p1-> number,&p1-> score[0],&p1-> score[1],&p1-> score[2]);
p1-> next=NULL;
if   (head==NULL)return   p1;
else
{
p2=head;
while(p2-> next!=NULL)p2=p2-> next;
p2-> next=p1;

return   head;
}

}
void   print(struct   student   *head)
{
struct   student   *p1;
p1=head;
while(p1!=NULL)
{
printf( "%d   %d   %d   %d\n ",p1-> number,p1-> score[0],p1-> score[1],p1-> score[2]);
        p1=p1-> next;
      }
}
main()
{       int   i;
struct   student   *head=NULL;
for   (i=0;i <5;i++)
head=creat(head);
print(head);
getch();
}


为什么会循环不下去!

[解决办法]
p1=(struct student*)malloc(sizeof(LEN));
~~~~~~~~~~~~~~?
[解决办法]

struct student *creat(struct student *head)
{
struct student *p1,*p2;
printf( "qingshuruxueshengshuju:\n ");
p1=(struct student*)malloc(sizeof(LEN));
if (p1==NULL)printf( "memory error:\n ");//此处既然分配失败就的返回,或者跑出异常,或者重新分配。
scanf( "%d%d%d%d%s%s%s ",&p1-> number,&p1-> score[0],&p1-> score[1],&p1-> score[2],p1-> name,p1-> sex,p1-> class);//在字符串结束后要加上结束符,不然肯定会出现乱码。

p1-> next=NULL;
if (head==NULL)return p1;
else
{
p2=head;
while(p2-> next!=NULL)p2=p2-> next;
p2-> next=p1;

return head;
}

}

void main()
{
int i;
struct student *head=NULL;
for (i=0; i <5; i++)
head=creat(head);
print(head);
getch();
}

ps 从效率上来说你问什么不在头结点处插入呢,

热点排行