要求是一个input
函数,它将 a 返回到从用户输入创建Node*
的链表的根。input
像:
Node *input()
{
Node *root; //not yet allocated
while(1)
{
//take in numbers from the user and correspondingly add them
//to the linked list and quit when anything else is entered
if(input character is a number)
{
//allocate memory to a fresh pointer and push the number to it
//and add this new Node to the LL
}
}
return root;
}
->在 while 循环体之前 有预分配内存root
并将第一个数字推送到它的解决方案。但是在这里,如果用户不输入任何内容,则必须立即删除。
->此外,还有一种可能的方法是在 while 循环中检查 root 是否为 NULL,如果是,则分配内存,以便它只发生一次。
但我想知道是否有解决方案可以消除由 LL 的根源引起的奇怪情况。
->也许我可以在第一个不包含任何值的虚拟节点。
但除此之外呢?如果有更好的方法来做整个事情,请提出建议。