我创建了这个代码来计算用户输入的链表中值的总和,预期的输出是打印总和,但它给出了最后一个值,并在链表中打印了错误数量的记录
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
。