Home > Enterprise >  How to pass values within functions in linked lists C
How to pass values within functions in linked lists C

Time:02-25

I created this code to calculate the sum of the values in a linked list entered by the user, and the expected output is to print the sum but it gives the last value and prints the wrong number of records in linked list

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 

My code is as below, however it does not print my expected output :

#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;
}

CodePudding user response:

In sumNodes(), you are declaring sum as a null pointer and then dereferencing it, which invokes undefined behavior.

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
}

There is no need to use a pointer at all. Instead, write:

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

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

    return sum;
}

CodePudding user response:

change double *sum to double sum, or better to int sum.

  • Related