注册 登录
编程论坛 C++教室

链表的输出出错,求指点啊

qq1625127317 发布于 2015-10-23 10:59, 495 次点击
大家看看就是这个链表,就是为什么数不出来啊?哪一点出了问题呢?
#include<iostream>
using namespace std;
struct student
{
    char name[30];
    struct student * pnext;
};
struct student * creat_list(struct student * h);     //建立链表函数
void print_list(struct student * h);                 //输出链表函数
void main()
{
    struct student * head;
        head = NULL;
    head = creat_list(head);    //建立链表
    print_list(head);           //输出链表
}
struct student * creat_list(struct student * h)     //建立链表函数定义
{
    struct student * p1,* p2;
    p1 = p2 = new student;
    if(p2 != NULL)
    {
        cin >> p2 -> name;
        p2 -> pnext = NULL;
    }
    while(p2 -> name[0] != '#')
    {
        if(h == NULL)
           h = p2;
        else
            p1 = p2;
        p1 = p2;
        p2 = new student;
        cin >> p2 -> name;
        p2 -> pnext = NULL;
    }
    return h;
}
void print_list(struct student * h)               //输出链表函数定义
{
    struct student * temp;
    temp = h;
    while(temp != NULL)
    {
        cout << temp -> name <<endl;
        temp = temp -> pnext;
    }
}
6 回复
#2
rjsp2015-10-23 11:49
我只知道链表是 std::list
#3
qq16251273172015-10-23 15:30
回复 2楼 rjsp
和C语言中的不一样?
#4
诸葛欧阳2015-10-23 16:02
    p1 = p2 = new student;
    if(p2 != NULL)
    {
        cin >> p2 -> name;
        p2 -> pnext = NULL;
    }
你确定分配内存成功?
#5
qq16251273172015-10-23 18:15
回复 4楼 诸葛欧阳
改了还是输出有问题。。。。比如我输入  张三 李四 王五 赵六 它输出的时候是只有 张三。。没有其他的,诶什么呢?
#6
yangfrancis2015-10-24 17:55
哪一步是把新元素赋给链尾没看到呢?
#7
qq16251273172015-10-24 18:13
回复 6楼 yangfrancis
多谢!看到了
1