Sebastian Miklosevic
Sebastian Miklosevic

Reputation: 15

Trying to understand why my linked list only show the last added node

So i'm lost right now the idea was to make a linked list where the user can add multiple school subjects and it needs to be displayed at the end but what i get is the last inserted subject and it's infromation at the end. Maybe someone can help?

#include <iostream>

using namespace std;
struct cvor {
    int sif_pred;
    string naz_pred;
    int br_sati_pr;
    int br_sati_vj;
    cvor* veza; //veza=link
} faks;
void unos(cvor*& glava, cvor* noviPredmet) //glava=head
{

    noviPredmet->sif_pred = faks.sif_pred;
    noviPredmet->naz_pred = faks.naz_pred;
    noviPredmet->br_sati_pr = faks.br_sati_pr;
    noviPredmet->br_sati_vj = faks.br_sati_vj;
    noviPredmet->veza = glava;
    glava = noviPredmet;
}
void ispis(cvor*& glava)
{
    while (glava) {
        cout << glava->sif_pred << " ";
        cout << glava->naz_pred << " ";
        cout << glava->br_sati_pr << " ";
        cout << glava->br_sati_vj << " ";
        glava = glava->veza;
    }
}
int main()
{
    cvor* glava = 0;
    cvor* noviPredmet = new cvor;
    int x;
    do {
        do {
            cout << "Unesti sifru predavanja: ";
            cin >> faks.sif_pred;
            cout << "\nUnesti naziv predavanja: ";
            cin >> faks.naz_pred;
            cout << "\nUnesti broj stai predavanja: ";
            cin >> faks.br_sati_pr;
            cout << "\nUnesti broj stai vjezbi: ";
            cin >> faks.br_sati_vj;
        } while (faks.br_sati_vj != 0);

        unos(glava, noviPredmet);
        cin >> x;
    } while (x != 0);
    ispis(glava);
    return 0;
}

Upvotes: 1

Views: 55

Answers (2)

Giogre
Giogre

Reputation: 1504

@DavidSchwartz is right, you should move this line in your code

cvor* noviPredmet = new cvor;

a couple of lines down, sandwiched between to two do commands and it should work as expected.

What is the role of variable x that breaks the outer loop? I have noticed that the code will print only the nodes that have been inserted in the last outer loop, the one with x = 0.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182763

You only allocate one node, here:

    cvor* noviPredmet = new cvor;

Then, every time, you add that very same node to the list:

        unos(glava, noviPredmet);

Upvotes: 1

Related Questions