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

创办链表出错,求解!

2013-05-02 
创建链表出错,求解!!!!#include stdio.h#include stdlib.hstruct Student{char No[11]char Name[11]

创建链表出错,求解!!!!

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

struct Student
{
char No[11];
char Name[11];
int Age;
};
struct Node
{
struct Student Stu;
struct Node *Next;
};

void CreateList(struct Node *Head);
void Output(struct Node *Head);

int main(void)
{
/*********Found************/
struct Node *Head; 

Head = (struct Node *)malloc(sizeof(struct Node));
Head->Next = NULL;
CreateList(Head);
Output(Head);

return 0;
}

void CreateList(struct Node *Head)
{
int i = 0;
char tmp[10];

do
{
struct Node *tt;

tt = (struct Node*)malloc(sizeof(struct Node));
printf("请输入学生的学号:");
gets(tt->Stu.No);
printf("请输入学生的姓名:");
gets(tt->Stu.Name);
printf("请输入学生的年龄:");
gets(tmp);
tt->Stu.Age = atoi(tmp);
tt->Next = Head->Next;//这句没看懂
/*********Found************/
i++;
if(i==1)
Head = tt;
else
{
Head->Next=tt;
}

printf("是否继续添加节点?(Y/N)");
gets(tmp);
} while (tmp[0]=='Y' || tmp[0]=='y');
    
}

void Output(struct Node *Head)//没问题
{
struct Node *p;

p = Head;
printf("全部学生信息如下:\n");
while (p!=NULL)
{
printf("%15s%15s%10d\n", p->Stu.No, p->Stu.Name, p->Stu.Age);
p = p->Next;
}
}
链表 C
[解决办法]
#include <stdio.h>
#include <stdlib.h>

struct Student
{
    char No[11];
    char Name[11];
    int Age;
};
struct Node
{
    struct Student Stu;
    struct Node *Next;
};

void CreateList(struct Node *Head);
void Output(struct Node *Head);

int main(void)
{
    /*********Found************/
    struct Node *Head;

    Head = (struct Node *)malloc(sizeof(struct Node));
    Head->Next = NULL;
    CreateList(Head);
    Output(Head);

    return 0;
}

void CreateList(struct Node *Head)
{
    int i = 0;
    char tmp[10];

    do
    {
        struct Node *tt;

        tt = (struct Node*)malloc(sizeof(struct Node));
        printf("请输入学生的学号:");
        gets(tt->Stu.No);
        printf("请输入学生的姓名:");
        gets(tt->Stu.Name);
        printf("请输入学生的年龄:");


        gets(tmp);
        tt->Stu.Age = atoi(tmp);
        tt->Next = Head->Next;//将新创建的节点插到头结点的后面
        /*********Found************/
        i++;
        if(i==1)
            Head->Next = tt;
        else
        {
            Head->Next=tt;
        }

        printf("是否继续添加节点?(Y/N)");
        gets(tmp);
    } while (tmp[0]=='Y' 
[解决办法]
 tmp[0]=='y');

}

void Output(struct Node *Head)//没问题
{
    struct Node *p;

    p = Head->Next;
    printf("全部学生信息如下:\n");
    while (p!=NULL)
    {
        printf("%15s%15s%10d\n", p->Stu.No, p->Stu.Name, p->Stu.Age);
        p = p->Next;
    }
}


在楼主的基础之上改的,楼主这里要CreateList函数注意一个问题,不能改变Head变量的值,要是要改变的话,就得传Head变量的地址进去。

热点排行
Bad Request.