Reputation: 15
We are asked to make a program using list structure to list student information but I can't seem to find a way to output all of it. It only shows one and it is the last input. I'm new in doing linked list so I do not know how to manipulate them. Any help will be much appreciated! Thank you guys!
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
struct StudList{
string studID, studName, Course;
int Yr_level;
StudList *next;
};
StudList *head;
head = NULL;
StudList *stud;
StudList *studptr;
int studNum;
system("color F0");
cout << "Enter number of stuedents: ";
cin >> studNum;
for (int i=1; i<=studNum; i++)
{
stud = new StudList;
cout << "\nEnter Student ID : ";
cin >> stud -> studID;
cout << "Enter Student Name : ";
cin >> stud -> studName;
cout << "Course : ";
cin >> stud -> Course;
cout << "Year Level : ";
cin >> stud -> Yr_level;
stud -> next = NULL;
cout << endl;
}
cout << "\nThe students are: ";
while (stud != NULL)
{
cout << endl << endl << left << setw(10) << stud -> studID << setw(10) << stud -> studName <<
setw(8) << stud -> Course << setw(4) << stud -> Yr_level;
stud = stud -> next;
}
if (head == NULL)
{
head == stud;
}
else
{
studptr = head;
while (studptr -> next)
{
studptr = studptr -> next;
}
studptr -> next = stud;
}
}
Upvotes: 0
Views: 64
Reputation: 86
In for
loop you should save new stud
object for setting stud->next
during next iteration.
In while
loop you are checking only last created stud
object. You must set stud
for the first object from the list, you can use head
object for that to save first list element.
I think that if (head == NULL) ...
part is not necessary.
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
struct StudList{
string studID, studName, Course;
int Yr_level;
StudList *next;
};
StudList *head;
head = NULL;
StudList *stud;
int studNum;
system("color F0");
cout << "Enter number of stuedents: ";
cin >> studNum;
StudList * temp = nullptr;
for (int i=1; i<=studNum; i++)
{
stud = new StudList;
if ( i == 1 )
{head = stud;}
else
{temp->next = stud;}
cout << "\nEnter Student ID : ";
cin >> stud -> studID;
cout << "Enter Student Name : ";
cin >> stud -> studName;
cout << "Course : ";
cin >> stud -> Course;
cout << "Year Level : ";
cin >> stud -> Yr_level;
stud -> next = NULL;
temp = stud;
cout << endl;
}
stud = head;
cout << "\nThe students are: ";
while (stud != NULL)
{
cout << endl << endl << left << setw(10) << stud -> studID << setw(10) << stud -> studName <<
setw(8) << stud -> Course << setw(4) << stud -> Yr_level;
stud = stud -> next;
}
}
Upvotes: 2