C语言链表问题

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{long num;
char name;
char publish;

struct student*next;
};
int n;
struct student*creat(void)
{
struct student*head;
struct student*p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
scanf("%ld,%c,%c",&p1->num,&p1->name,&p1->publish);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld,%c,%c",&p1->num,&p1->name,&p1->publish);
}
p2->next=NULL;
return(head);
}

int main()
{struct student*pt;
pt=creat();
printf("\nnum:%ld\nname:%c\npublish:%c\n",pt->num,pt->name,pt->publish);
return 0;
};
问下我这个在执行的的时候为什么不能输入第二行 而且也输出不了 求达人指教

第1个回答  2012-06-04
你这个name为什么是字符类型?而不是字符数组?
再有你这个输入会有问题,要小心,因为程序是数字后边不能有空格,否则空格给了name,例如你输入:12345 n k那么12345赋值给了num成员,空格给了name,n给了publish,那么下一次输入的时候k就给了下一个节点的num成员,这样就出现了问题追问

恩恩 那问下输入的时候应该怎么输?我看书上的逗号隔开,但是自己输的时候又不行了

追答

输入的时候应该是123456,n,c加回车,之间不能有空格

第2个回答  2012-06-04
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student{
long num;
char name;
char publish;
struct student *next;
};

struct student *creat(void) //这种是后插法创建链表
{
struct student *head = NULL;
struct student *p, *tail;
p = (struct student*)malloc(LEN);
scanf("%ld,%c,%c",&p->num,&p->name,&p->publish);
p->next = NULL;
head=NULL;
if (p->num == 0) //首次输入如果p->num为0,返回NULL
{
free(p);
return head;
}
else
{
while(1)
{
if (head == NULL)
{
head = p;
tail = p;
}
else
{
tail->next=p;
tail = p;
}
p = (struct student*)malloc(LEN);
scanf("%ld,%c,%c",&p->num,&p->name,&p->publish);
p->next = NULL;
if (p->num == 0) //结束条件,p->num = 0时返回创建成功的链表的头指针
{
free(p);
return head;
}
}//end while
}
}

void print_stu(struct student *head) //输出链表要用遍历的方法
{
struct student *p = head;
while (p != NULL)
{
printf("\nnum:%ld\nname:%c\npublish:%c\n",p->num,p->name,p->publish);
p = p->next;
}
}

int main(void)
{
struct student *pt;
pt=creat();
print_stu(pt);

return 0;
}
另外:你的创建链表函数问题太多,说明白很费劲追问

那个我想输入两个字符怎么办 貌似输入123,er,rt就会悲剧了,还有能留下联系方式不,还有好些想问的 先谢了

本回答被提问者采纳
相似回答