Nó de Lista ligado em C++ com classe

especificamente, o objetivo aqui é criar uma estrutura vinculada que tenha algum Número de nós, entre 5 e 2 milhões. Não se preocupe que este número é grande ou que os valores podem envolver em torno do tamanho máximo do inteiro. Se você criou sua estrutura conectada corretamente, um computador moderno pode atravessar este código muito rapidamente. Note que os comentários descrevem exatamente como este main deve funcionar. Aqui estão os destaques:

Criar três laços O primeiro ciclo cria o estrutura ligada, juntando os campos "próximos" de cada nó e dando a cada nó um valor inteiro entre 0 e o tamanho escolhido aleatoriamente. O segundo loop adiciona todos os nós e os Conta. A contagem dos nós neste caso deve ser usada apenas como verificação para se certificar de que você não está faltando um. O terceiro loop atravessa todos os nós novamente, desta vez apagando-os.

nó.h

class Node {
public:
    Node();
    Node(const Node& orig);
    virtual ~Node();
    bool hasNext();
    Node* getNext();
    void setNext(Node* newNext);
    int getValue();
    void setValue(int val);
private:
    Node* next;
    int value;
};

#endif

nó.cpp

include "Node.h"
include <iostream>

Node::Node() {
    next = NULL;
}

Node::Node(const Node& orig) {
    next = orig.next;
    value = orig.value;
}

Node::~Node() {

}

bool Node::hasNext(){
    if (next != NULL)
        return true;
    else
        return false;
}

Node* Node::getNext(){
    return next;
}

void Node::setNext(Node* newNext){
    if(newNext == NULL)
        next = NULL;
    else
        next = newNext->next;
}

int Node::getValue(){
    return value;
}

void Node::setValue(int val){
    value = val;
}

principal.cpp

include <cstdlib>
include <iostream>
include "Node.h"
include <time.h>

using namespace std;

int main(int argc, char** argv) {
    //This is the node that starts it all
    Node *tail;
    Node* head = new Node();

    //select a random number between 5 and 2,000,000
    srand(time(NULL));
    int size = (rand() % 2000000) + 5;
    int total = 0;
    int counter = 0;
    //print out the size of the list that will be created/destroyed
    cout << "The total size is: " << size << endl;

    head->setValue(0);
    tail = head;
    Node *newNode = new Node;
    for (int i = 1; i < size; i++){  
        Node *newNode = new Node;
        newNode->setValue(i);
        newNode->setNext(NULL);
        tail->setNext(newNode);
        tail = newNode;
    }

    //Create a list that counts from 0 to 2,000,000
    //Link all of the nodes together
    //A for loop is easiest here
    cout << head->getNext()->getValue();

    Node* current = head;
    while (current != NULL){ 
        counter += current->getValue();
        cout << current->getValue();
        current = current->getNext();
        total++;
    }

    //Traverse the list you created and add up all of the values
    //Use a while loop

    //output the number of nodes. In addition, print out the sum
    //of all of the values of the nodes.
    cout << "Tracked " << total << " nodes, with a total count of " << counter << endl;

    //Now loop through your linked structure a third time and
    //delete all of the nodes
    //Again, I require you use a while loop

    cout << "Deleted " << total << " nodes. We're done!" << endl;
    return 0;
}

está a imprimir o tamanho total entao... Estou a ter uma falha de Seg: 11. Eu também estou faltando algumas partes na parte principal, eu estou confuso sobre como escrever estes também.

 6
Author: bstrauch24, 2014-03-11

1 answers

Deve ser next = newNext; em vez de next = newNext->next;

void Node::setNext(Node* newNext){
    if(newNext == NULL)
        next = NULL;
    else
        next = newNext;
}
 4
Author: michaeltang, 2014-03-11 01:30:15