我在显示链接列表中的数据时遇到问题。我尝试将显示循环包含在 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/