我正在编写一些用户可以输入某些信息的代码;然后被推回到一个链表......除了这个因为这些行在这里有一个额外的0被添加到列表末尾之外,所有这些都是有用的:
用户如何输入信息:
int sizeOf = 0, i = 0, itemStock = 0;//, individualItemCost = 0;
string name;
double individualItemCost = 0;
cout << "How many lines would you like to input: " << endl;
cin >> sizeOf;
//Create a head node(first element)...
Stock* head = buildNode(name, itemStock, individualItemCost);
//Each time, create a new node and push onto the list...
while (i < sizeOf)
{
/*cout << "Please enter the students name: " << endl;
cin >> head->itemName;
cout << "Please enter the item stock: " << endl;
cin >> head->itemStock;
cout << "Please enter the item price: " << endl;
cin >> head->individualItemCost; */
cout << "Please enter the students name: " << endl;
cin >> name;
cout << "Please enter the item stock: " << endl;
cin >> itemStock;
cout << "Please enter the item price: " << endl;
cin >> individualItemCost;
//push(head,head->itemName, head->itemStock, head->individualItemCost); //Push back everything in head
push(head,name, itemStock, individualItemCost); //Push back everything in head
i++;
}
Buildnode功能:
Stock* buildNode(string itemName, int itemStock, double individualItemCost)
{
Stock* s = new Stock;
s->itemName = itemName;
s->itemStock = itemStock;
s->individualItemCost = individualItemCost;
s->next = nullptr;
return s;
}
我如何将ti推到列表中:
void push(struct Stock*& list, string itemName, int itemStock, double individualItemCost)
{
Stock* newnode = new Stock;
newnode->itemName = itemName;
newnode->itemStock = itemStock;
newnode->individualItemCost = individualItemCost;
newnode->next = list;
list = newnode;
}
我只需要输入用户输入的内容,而不是头部。
答案 0 :(得分:0)
为什么要使用具有head
值的节点初始化0
?
这样想,启动时,head
是null
..
当您的push
方法在列表的前面添加新节点时,即使列表中没有任何其他节点,它也会添加一个新节点。你只需要换行
Stock* head = buildNode(name, itemStock, individualItemCost);
到
Stock* head = null;
希望它有所帮助...