带类的C ++链接列表节点

时间:2014-03-11 00:59:44

标签: c++ class

具体来说,这里的目标是创建一个链接结构,该结构具有一定数量的节点,介于5到200万之间。不要担心这个数字很大,或者值可能会超过整数的最大值。如果您已正确创建链接结构,现代计算机可以非常快速地轻松完成此代码。请注意,这些注释确切地描述了该main应该如何工作。以下是重点:

创建三个循环 第一个循环创建链接结构,将每个节点的“下一个”字段连接在一起,并为每个节点提供介于0和随机选择大小之间的整数值。 第二个循环将所有节点相加并计算它们。在这种情况下计算节点应该仅用作检查以确保您没有遗漏。 第三个循环再次遍历所有节点,这次删除它们。

Node.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

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

的main.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;
}

打印出总尺寸然后...... 我得到了一个Seg故障:11。 我也缺少一些主要的部分,我也很困惑如何写这些。

1 个答案:

答案 0 :(得分:4)

应该是next = newNext;而不是next = newNext->next;

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