Witam,
Przy wypisywaniu elementów z listy dwukierunkowej program psuje się zawsze przy wypisywaniu ostatniego elementu tzn. wypisuje wszystkie elementy z listy, a gdy ma wypisać ostatni element wyrzuca błąd.
Podejrzewam, że gdzieś źle ustawiam wskaźnik na następny element, ale nie wiem gdzie. Wrzucam kod, proszę o przeglądnięcie i pomoc
#include <iostream>
#include <cstdlib>
using namespace std;
struct element {
int date;
element* next;
element* previous;
};
struct lista {
element* head;
element* tail;
int liczba_el = 0;
};
void add_last(lista& l);
void add_first(lista& l);
void show_list(lista l);
int main()
{
lista l;
add_first(l);
add_last(l);
add_first(l);
add_first(l);
show_list(l);
return 0;
}
void add_last(lista& l)
{
int a;
element* nowy = new element;
cout << "Podaj wartosc do dodania na koniec\n";
cin >> a;
nowy->date = a;
nowy->next = nullptr;
nowy->previous = nullptr;
if (l.tail != nullptr) {
l.tail->next = nowy;
nowy->previous = l.tail;
}
l.tail = nowy;
if (l.head == nullptr) {
l.head = nowy;
}
l.liczba_el = l.liczba_el + 1;
}
void add_first(lista& l)
{
int a;
element* nowy = new element;
cout << "Podaj liczbe do dodania na poczatek\n";
cin >> a;
nowy->date = a;
nowy->next = nullptr;
nowy->previous = nullptr;
if (l.head != nullptr) {
l.head->previous = nowy;
nowy->next = l.head;
}
l.head = nowy;
if (l.tail == nullptr) {
l.tail = nowy;
}
l.liczba_el = l.liczba_el + 1;
}
void show_list(lista l)
{
element* temp = l.head;
for (int i = 1; i <= l.liczba_el; i++) {
cout << "Liczba nr to " << i << " ";
cout << temp->date << endl;
temp = temp->next;
}
}