获取用户输入以形成链表
getting user input to form linked list
我正在尝试从用户输入创建一个链表,但当我尝试打印它时它没有打印任何东西。连头都没有。另请注意,它是故意向后移动的。
这是我获取用户输入的函数,它返回列表。我知道这是错误的,但我花了几个小时,无法让它工作......
#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;
}
}
get input(( 的返回值不是列表的实际头/开头。当您插入任何节点时,head 将始终指向 null。在首次插入期间,head 值可以存储在临时指针中,并返回临时指针而不是 head。
如果您尝试以相反的顺序打印链表,这里有一个工作版本:
#include <iostream>
#include <limits>
#include <ios>
using namespace std;
struct Node {
int value;
Node *next;
Node(int val, Node *nextPtr) {
value = val;
next = nextPtr;
}
};
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 = tmp;
}
}
return head;
}
int main() {
Node *head = getInput();
Node *tmp;
while (head != nullptr) {
cout << head->value << ", ";
tmp = head;
head = head->next;
delete tmp;
}
cout << endl;
return 0;
}
head = head->next;
是问题所在。 您正确地分配了Node
,但您立即泄漏了该Node
,head
指向nullptr
。
最简单的解决方案是保持head
指向 最新的Node
. 第一次插入需要特殊情况,因为head
将未初始化(顺便修复一下(,但这样您始终指向最新的Node
。
如果您遇到问题,请用箭头在纸上画出Node
。 观察每次插入时箭头的变化,您将看到发生了什么。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 如何实现链表并允许用户选择要使用 C++ 删除的特定节点?
- 获取用户输入以形成链表
- 用户定义的链表从函数返回指针
- 链表程序在收到来自用户的值后崩溃
- 从用户输入创建和打印链表