这个C语言链表程序哪错了?运行过就给分,别说大道理.

来源:百度知道 编辑:UC知道 时间:2024/06/23 04:39:17
大家好,我看不出这个哪错了,可是运行时,不能输出所有元素,总是只是输出最后一个元素无数次,哪里出错了?

#include<stdio.h>
struct snode
{
char name[15];
struct snode *next;
};

struct snode *create_list(int n)
{
int i;
struct snode *head,*tail,*p; /*struct snode *head,*p; */
head=tail=NULL; /*定义了一个空链表,空链表的首尾指针都是null*/
for(i=0;i<n;i++)
{
p=(struct snode *)malloc(sizeof(struct snode)); /*分配一个动态空间,把首址给p*/
scanf("%s",p->name); /*把值给p所指向的地址*/
p->next=NULL; /*把p所指向的下一个元素令为尾元素,因为还没有给值给它*/
if(head==NULL) /*如果是空链表*/
head=tail=p; /*就把分配的空间首始给首尾元素的地址*/
else
{
tail->next=p; /*要不就把分配的空间地址给下一个元素*/
}
}
return head; /*返回的是首元素的地址*/
}

main()
{
struct snode *q;
q=create_list(5); /*首元素的地址给予q*/
while(q!=NULL)
{
printf("%s\n",q->name); /*打印元素*/
q=q->next; /*指向下一个元素*/
}<

试试能否运行过吧

#include <stdio.h>
#include <stdlib.h>

struct snode
{
char name[15];
struct snode *next;
};

struct snode *create_list(int n)
{
int i;
struct snode *head,*tail,*p; /*struct snode *head,*p; */
head=tail=NULL; /*定义了一个空链表,空链表的首尾指针都是null*/
for(i=0;i<n;i++)
{
p=(struct snode *)malloc(sizeof(struct snode)); /*分配一个动态空间,把首址给p*/
scanf("%s",p->name); /*把值给p所指向的地址*/
p->next=NULL; /*把p所指向的下一个元素令为尾元素,因为还没有给值给它*/
if(head==NULL) /*如果是空链表*/
head=tail=p; /*就把分配的空间首始给首尾元素的地址*/
else
{
tail->next=p; /*要不就把分配的空间地址给下一个元素*/
}
}
return head; /*返回的是首元素的地址*/
}

void main()
{
struct snode *q;
q=create_list(5); /*首元素的地址给予q*/
while(q!=NULL)
{
printf("%s\n",q->name); /*打印元素*/
q=q->next; /*指向下一个元素*/
}
}

你创建链表时少了一句