Dynamic vector using Struct

Dynamic vector using Struct

本文关键字:Struct using vector Dynamic      更新时间:2023-10-16

我有这个结构:

struct Node {
int number;
Node *next;
};

和这个类插入元素并显示向量:

// 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;
};

这就是实现:

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;
}
}

在主要功能中,我写道:

#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;
}

我不知道为什么,但它只显示了最后两个数字。有人知道为什么吗?

它只显示最后两个数字,因为当您插入新数字时,您将头移动到下一个节点。有两个选项可以打印整个矢量。

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
Node* temp2 = this->p;
while (temp2->next != NULL) {
temp2 = temp2->next;
}
temporary->number = number;
temporary->next   = NULL;
// In questo passaggio copiamo la struttura
// temporanea "temporary" nell' ultima struttura "p"
temp2->next = temporary;
}

或者在main()中,存储向量的第一个节点的位置,并将其用于打印

DynamicVector *vector = new DynamicVector();
DynamicVector *vector2 = vector;
...
vector2->ShowVector();
while (this->p->next != NULL) {
this->p = this->p->next;
}

在这段代码中,您可以跳过所有现有节点,这些节点将丢失。即当p不为NULL时调用它,然后将p重置为NULL。该代码没有意义,它等于p=NULL。

要么改变这个,要么做

vector->InsertNumber(5)->InsertNumber(3)->InsertNumber(6)->InsertNumber(22);

(您必须从InsertNumber返回"this");

或者两者都可以。