c++ - 显示链接列表

标签 c++ linked-list

我在显示链接列表中的数据时遇到问题。我尝试将显示循环包含在 for 循环中并包含在 for 循环中,只是为了检查指针和数据是否有问题,但我得到了相同的结果。

它显示第一个数据,但随后开始显示乱码。

#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <string>

void main(void) {
    clrscr();
    struct Student {
        string Name;
        double GPA;
        Student *next;
    };

    Student *head;
    head = NULL;

    int ch, i;
    string name;
    double gpa;

    cout << "How Many Records Do You Want To Enter?";
    cin >> ch;
    cout << endl;

    for (i = 0; i < ch; i++) {
        cout << (i + 1) << ". Name Of Student:";
        cin >> name;
        cout << "GPA Of Student:";
        cin >> gpa;
        cout << endl;

        Student *newstudent;
        Student *studentptr;

        newstudent = new Student;
        newstudent->Name = name;
        newstudent->GPA = gpa;
        newstudent->next = NULL;

        if (!head)
            head = newstudent;
        else {
            studentptr = head;

            while (studentptr->next) {
                studentptr = studentptr->next;
            }
            studentptr->next = new Student;
        }
    }

    clrscr();
    Student *display;
    display = head;

    while (display) {
        cout << "Name:" << display->Name << endl;
        cout << "GPA:" << display->GPA << endl;

        display = display->next;
    }
    getch();
}

有什么建议和正确方向的指示吗?

显然我正在遵循某人的教程,但发生了此错误。

最佳答案

studentptr->next = new Student; 应该是 studentptr->next = newstudent;

关于c++ - 显示链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480803/

相关文章:

c++ - 如何让编译器在赋值时计算出模板类参数?

c++ - GTEST : False negative for incorrect number of macro arguments

c - c中的pf apply是什么?

java - 使用java在特定位置插入节点

c++ - c++ if语句中的多个条件(通过链表的堆栈实现)

c++ - 如何使用 LiquidCrystal 在 Arduino 中创建我自己的库?

c++ - 如何启用 Eclipse 以在运行前自动构建/自动保存更改 (CDT)

C++没有main()函数?

java - Java中无法正确排序到达时间

php - 在php中实现链表