Witam, zacząłem ćwiczyć używanie dynamicznych struktur, metod struktur, konstruktorów, inicjalizatorów itd. Chciałem stworzyć listę jednokierunkową (struct LinkedList) przechowującą dane studentów (struct Student). Metoda printAll() struktury LinkedList służy do wypisania całej listy. W poniższym kodzie próbuję wypisać listę, usunąć pierwszy element listy (lista.deleteHead()) i wypisać listę ponownie. Problem w tym, że na konsoli wyświetla mi się jedna pofragmentowana lista, niektóre pola struktur są zastąpione pustymi liniami, co uruchomienie jest inaczej. Nie wyświetla mi się informacja o zakończonym programie. Poniżej kod:
#include <iostream>
using namespace std;
struct Student
{
string imie;
string email;
int id;
double srednia;
Student* nastepny;
void print();
Student(string imie, string email, int id, double srednia);
};
struct LinkedList
{
Student* pierwszy;
Student* ptr;
void printAll();
void addHead(Student* student);
void deleteAll();
void deleteHead();
LinkedList();
};
Student::Student(string imie, string email, int id, double srednia)
: imie(imie)
, email(email)
, id(id)
, srednia(srednia)
{
nastepny = NULL;
}
LinkedList::LinkedList()
{
pierwszy = NULL;
}
void Student::print()
{
cout << "Imie: " << imie << endl;
cout << "Email: " << email << endl;
cout << "ID: " << id << endl;
cout << "Srednia: " << srednia << endl;
}
void LinkedList::printAll()
{
ptr = pierwszy;
while(ptr)
{
ptr->print();
ptr=ptr->nastepny;
}
}
void LinkedList::addHead(Student* nowy)
{
if(pierwszy == 0)
pierwszy = nowy;
else
{
nowy->nastepny = pierwszy;
pierwszy = nowy;
}
}
void LinkedList::deleteAll()
{
while(pierwszy)
{
ptr = pierwszy;
pierwszy = pierwszy->nastepny;
delete ptr;
}
}
void LinkedList::deleteHead()
{
if(pierwszy != 0)
{
ptr = pierwszy;
pierwszy = ptr->nastepny;
delete ptr;
}
}
int main()
{
LinkedList lista;
Student* A = new Student("Maciej", "maciej@gmail.com", 247682, 4.5);
Student* B = new Student("Kamil", "kamil@gmail.com", 247683, 5.0);
Student* C = new Student("Adam", "adam@gmail.com", 247684, 4.0);
Student* D = new Student("Jan", "jan@gmail.com", 247689, 3.5);
Student* E = new Student("Piotr", "piotr@gmail.com", 247690, 3.0);
lista.addHead(A);
lista.addHead(B);
lista.addHead(C);
lista.addHead(D);
lista.addHead(E);
lista.printAll();
cout << endl;
lista.deleteHead();
lista.printAll();
lista.deleteAll();
return 0;
}
Kiedy wypisuję listę jednokrotnie w całym programie, to wyświetla się ona prawidłowo. Jak wspominałem, problem pojawia się, gdy próbuję wypisać listę więcej razy.
Jak na razie niepewnie poruszam się w temacie wskaźników jeżeli chodzi o listy, więc myślę że problem może być związany z jakąś błędną operacją na wskaźniku, chociaż, oczywiście, mogę myśleć źle :)