'Why does it print a 0 in the output?

How do I get rid of this 0 in the output? I think the problem is with the function called printReceipt.

#include <iostream>
using namespace std;


struct Node
{
    string name;
    int price;
    Node *link;
};


// Insert Node with value new_name at the end of the linked list
// whose first node is head_ref
void appendName(Node** head_ref, string new_name)
{
    Node* newNode = new Node();
    Node *last = *head_ref;
    newNode->name = new_name;
    newNode->link = NULL;
    if (*head_ref == NULL)
    {
        *head_ref = newNode;
        return;
    }
    while (last->link != NULL)
    {
        last = last->link;
    }
    last->link = newNode;
    return;
}

// Insert Node with price new_price at the end of the linked list
// whose first node is head_ref
void appendPrice(Node** head_ref, int new_price)
{
    Node* newNode = new Node();
    Node *last = *head_ref;
    newNode->price = new_price;
    newNode->link = NULL;
    if (*head_ref == NULL)
    {
        *head_ref = newNode;
        return;
    }
    while (last->link != NULL)
    {
        last = last->link;
    }
    last->link = newNode;
    return;
}

// Print the linked list
void printReceipt(Node *node)
{
    while (node != NULL)
    {
        cout<<" "<<node->name<<" "<<node->price;
        node = node->link;
    }
    
}


int main()
{
    Node* r1 = NULL;

    appendName(&r1, "Item#1");
    appendPrice(&r1, 23);
    

    cout<<"Receipt\n";

    printReceipt(r1);
    return 0;
}

Program output:

Receipt
 Item#1 0 23

https://i.stack.imgur.com/FwGgL.png



Solution 1:[1]

The problem you are having is because you have 2 Nodes. One that has "Item#1" as the name property and 0 as price and another one that has no name set and 23 as the price. I went ahead and changed the output for you so you can see in more detail what's going on:

void printReceipt(Node *node)
{
    while (node != NULL)
    {
        printf("Address: %x\n", node);
        cout << "Name: " << node->name << endl;
        cout << "Price: " << node->price << endl;
        node = node->link;
    }
}

It shows us the Adress of the node and the contents:

Receipt
Address: c9eedeb0
Name: Item#1
Price: 0
Address: c9eedef0
Name:
Price: 23

As you can see the first address ends with b0 and the second one ends with f0.

The error is inside your appendPrice function. In there you first add the price to the new Node but then at the end put the new Node address in the link of the old node.

last->link = newNode;
return;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sebito