获取用户输入以形成链表

getting user input to form linked list

本文关键字:链表 用户 输入 获取      更新时间:2023-10-16

我正在尝试从用户输入创建一个链表,但当我尝试打印它时它没有打印任何东西。连头都没有。另请注意,它是故意向后移动的。

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

#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,但您立即泄漏了该Nodehead指向nullptr

最简单的解决方案是保持head指向 最新的Node . 第一次插入需要特殊情况,因为head将未初始化(顺便修复一下(,但这样您始终指向最新的Node

如果您遇到问题,请用箭头在纸上画出Node。 观察每次插入时箭头的变化,您将看到发生了什么。