链接列表显示垃圾字符

时间:2018-09-21 22:43:19

标签: c++ visual-studio linked-list visual-studio-2017 c++17

不知道为什么,但是每次我显示链接列表时,它只会显示垃圾字符。当我在第31行中添加_getche并在_putch(current->c);的第53行显示值时,就会发生此问题。如果有人可以帮助描述我的问题,并提供非常感谢的解决方案! / p>

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

class ListNode
{
public:
    char c;
    ListNode *next;
};

int main()
{
    ofstream outputFile;
    ListNode *current;
    ListNode *start;
    ListNode *newNode = new ListNode();

    current = nullptr;
    start = newNode;
    newNode->next = nullptr;;

    cout << "Hit 'esc' when you are done.\n";
    while (newNode->c = _getche() != 27)
    {
        //If start is empty, create node
        if (current == nullptr)
        {
            current = newNode;
        }
        else //If start is not empty, create new node, set next to the new node
        {
            current->next = newNode;
            current = newNode;
        }

        newNode = new ListNode();
        newNode->next = nullptr;
    }

    //Display linked list
    cout << "Here is what you have typed so far:\n";
    current = start;
    while (current != nullptr)
    {
        _putch(current->c);
        current = current->next;
    }
    cout << endl;

    outputFile.close();
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在:

while (newNode->c = _getche() != 27)

=的{​​{3}}比!=低,因此将_getche() != 27的结果分配给newNode->c

修复:

while((newNode->c = _getche()) != 27)

通过维护指向ptail的最后一个节点的next指针,可以更容易地完成附加单链接列表:

head