gpt4 book ai didi

c++ - 获取用户输入以形成链表

转载 作者:行者123 更新时间:2023-11-27 23:47:34 25 4
gpt4 key购买 nike

我正在尝试根据用户输入创建一个链接列表,但是当我尝试打印它时它没有打印任何内容。连头都没有。另请注意,它是故意向后的。

这是我获取用户输入的函数,它返回列表。我知道这是错误的,但我已经花了几个小时,但无法让它工作......

#include <iostream>
#include <limits>
#include <ios>

struct Node {
int value;
Node *next;
}

Node* getInput() {
Node* head = nullptr;
Node* tmp;
while (true) {
int x;
if (!(cin >> x)) {
break;
} else if ( head == nullptr) {
head = new Node{x, nullptr);
} else {
tmp = new Node{x , nullptr};
tmp->next = head;
head = head->next;
}
}
return tmp;
}

int main() {
cout << getInput()->value;
}

最佳答案

提出了几个很好的解决方案,但因为请求是一个向后列表,所以这可能非常非常简单。

Node* getInput()
{
Node* head = nullptr;
int x;
while (std::cin >> x) // keep going until we can't get a good x.
{
head = new Node{x, head}; // point node at current head, assign new head
// head always points at the beginning of list because items are
// always inserted at the start of the list.
}
return head;
}

为了证明这个列表向后打印,这里有一个简单的测试器

int main()
{
Node* cur = getInput();
while (cur)
{
std::cout << cur->value << '\n';
cur = cur->next;
}
}

关于c++ - 获取用户输入以形成链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49375912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com