我創建了這段代碼來計算用戶輸入的鏈表中值的總和,預期的輸出是列印總和,但它給出了最后一個值并列印了鏈表中錯誤的記錄數
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;
}
uj5u.com熱心網友回復:
在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;
}
uj5u.com熱心網友回復:
改成double *sum,double sum或者更好int sum。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432200.html
上一篇:C 行內初始化靜態函式成員
下一篇:通過類方法附加HTML內容
