I’ve this struct:
struct Node {
int number;
Node *next;
};
and this class to insert element and show the vector:
// Classe DynamicVector :
// e' la classe che consente di inserire elementi
// e visualizzare il vettore di strutture
class DynamicVector
{
public:
DynamicVector();
void InsertNumber(int number);
void ShowVector();
protected:
Node *p;
};
This is the implementation:
DynamicVector::DynamicVector() {
this->p = NULL;
}
void DynamicVector::InsertNumber(int number) {
Node *temporary = new Node;
// Possiamo avere due possibili casi:
// non e' stato ancora inserito nessun elemento
// ...
if (this->p == NULL) {
temporary->number = number;
temporary->next = NULL;
this->p = temporary;
// ...
// oppure dobbiamo aggiungerne uno alla fine
// In questo caso meglio dire, lo "accodiamo"
} else {
// Sfogliamo le strutture fino a giungere
// all' ultima creata
while (this->p->next != NULL) {
this->p = this->p->next;
}
temporary->number = number;
temporary->next = NULL;
// In questo passaggio copiamo la struttura
// temporanea "temporary" nell' ultima struttura "p"
this->p->next = temporary;
}
}
void DynamicVector::ShowVector() {
while (this->p != NULL) {
std::cout << this->p->number << std::endl;
this->p = this->p->next;
}
}
In the main function I wrote this:
#include <iostream>
#include <conio.h>
#include "dynamic_vector.h"
int main() {
DynamicVector *vector = new DynamicVector();
vector->InsertNumber(5);
vector->InsertNumber(3);
vector->InsertNumber(6);
vector->InsertNumber(22);
vector->ShowVector();
delete vector;
getch();
return 0;
}
I dont’ know why but it show me only the last two number.
Someone know why?
It is only showing the last two numbers because when you are inserting new numbers, you are moving the head to the next Node. You have two options to get the entire vector to print.
or in main(), store the location of the first node of the vector, and use that for printing