如何在链表 C++ 的函数内传递值

How to pass values within functions in linked lists C++

我创建此代码是为了计算用户输入的链表中值的总和,预期的输出是打印总和,但它给出了最后一个值并在链表中打印了错误的记录数

Enter a number : 5
Enter [Y] to add another number : Y
Enter a number : 1
Enter [Y] to add another number : N
List of existing record : 5 
1 

我的代码如下,但是它没有打印出我预期的输出:

#include <iostream>    
using namespace std;    
class Node {
public:
    int no;
    Node* next; //missing code
};

Node* createNode(int num) {
    Node* n = new Node();
    n->no = num;
    n->next = NULL;
    return n;
}

void addValue(int no, Node** h) {
    //insert first node into linked list
    Node* y = createNode(no), * p = *h;
    if (*h == NULL)
        *h = y;
    //insert second node onwards into linked list
    else {
        while (p->next != NULL) //while not the end
            p = p->next;    // go next
        p->next = y;
    }
}    
void display(Node* x) {
    while (x != NULL) {
        cout << x->no << " " << endl;
        x = x->next;
    }
}
double sumNodes(Node** h) {
    double* sum = 0;
    Node* x = *h;

    while (x != NULL) {
        *sum += x->no;
        x = x->next;
    }

    return *sum;
}

int main() {
    int num = 0;  char choice;
    Node* head = NULL;
    double s;
    do {
        cout << "Enter a number : ";
        cin >> num;
        addValue(num, &head);
        cout << "Enter [Y] to add another number : ";
        cin >> choice;
    } while (choice == 'Y');    
    cout << "List of existing record : ";
    display(head);    
    cout << endl << endl;
    s = sumNodes(&head);
    cout << "Sum = " << s << endl;
    return 0;
}

sumNodes() 中,您将 sum 声明为空指针,然后取消引用它,这会调用未定义的行为。

double sumNodes(Node** h) {
    double* sum = 0; // <-- null pointer
    Node* x = *h;

    while (x != NULL) {
        *sum += x->no; // <-- dereference
        x = x->next;
    }

    return *sum; // <-- dereference
}

根本不需要使用指针。相反,写:

double sumNodes( const Node** h) {
    double sum = 0;
    const Node* x = *h;

    while (x != NULL) {
        sum += x->no;
        x = x->next;
    }

    return sum;
}

double *sum 更改为 double sum,或更好地更改为 int sum