[英]Why does it print a 0 in the output?
我如何擺脫 output 中的這個 0? 我認為問題出在名為 printReceipt 的 function 上。
#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;
}
程序 output:
Receipt
Item#1 0 23
您遇到的問題是因為您有 2 個節點。 一個名稱屬性為“Item#1”,價格為 0,另一個沒有設置名稱,價格為 23。 我繼續為您更改了 output,以便您可以更詳細地了解發生了什么:
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;
}
}
它向我們展示了節點的地址和內容:
Receipt
Address: c9eedeb0
Name: Item#1
Price: 0
Address: c9eedef0
Name:
Price: 23
如您所見,第一個地址以b0
結尾,第二個地址以f0
結尾。
錯誤在您的appendPrice
function 中。在那里您首先將價格添加到新節點,但最后將新節點地址放入舊節點的鏈接中。
last->link = newNode;
return;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.