LinkedList构造函数,允许用户输入列表中的元素

奥斯丁

最终编辑:感谢所有人的帮助,我知道为什么现在不起作用。

感谢ravi,对答案进行编辑,尽管我仍然不完全理解为什么每次都需要分配内存:

for (int i = 1; i < size; i++)
{
    cin >> input;
    newNode = new Node; //added this to make it work properly
    newNode->info = input;
    newNode->next = cursor;
    cursor = newNode;
}

原始问题:

我在弄清楚如何使其工作方面遇到了很多麻烦。

问题是:IntegerSet(int size):此构造函数方法通过提示用户在键盘上输入该大小整数元素的集合来创建新的大小整数集合。

截至目前,如果size等于3,并且用户输入了1、2、3,则在调用display()时,程序只会输出3,然后结束。我在构造函数代码中评论了我认为应该发生的事情,这显然不像我认为的那样。如果有人可以向我解释哪一部分(或者我完全不在话下),我会很困惑,我将不胜感激。

这是我的标题:

#include <iostream>
using namespace std;

template <class T>
class IntegerSet
{
private:
    class Node
    {
    public:
        T info;
        Node *next;
    };
    typedef Node *nodePtr;
    nodePtr first;
public:
    IntegerSet(int size);
    void display();
};
template <class T>
IntegerSet<T>::IntegerSet(int size)
{
    nodePtr newNode = new Node;
    int input;
    cout << "Enter " << size << " elements" << endl;
    cin >> input;
    newNode->info = input; //sets newNodes first element to input
    newNode->next = 0; //sets newNodes next to null
    nodePtr cursor = newNode; //make a cursor = to newNode, which should be input then 0
    for (int i = 1; i < size; i++)
    {
        cin >> input;
        newNode->info = input; //sets newNodes first element to a new input
        newNode->next = cursor; //sets newNodes next to cursor
        cursor = newNode; //sets cursor = to newNode, so after the first run through of the loop
                          //if the user entered 1 then 2, cursor would be 2->1->0
    }
    cursor->next = 0; //this is only here because it isn't working right in the first place.
                      //If this wasn't here then the program just infinitely loops with the last
                      //element entered when display is called
    first = cursor;
}

template <class T>
void IntegerSet<T>::display()
{
    nodePtr cursor = first;
    if (isEmpty())
    {
        cout << "There are no elements in the set" << endl;
        return;
    }
    while (cursor != 0)
    {
        cout << cursor->info << " ";
        cursor = cursor->next;
    }
    cout << endl;
}

主要的:

#include "header.h"

int main()
{
    IntegerSet<int> list(3);
    list.display();

    return 0;
}
拉维
for (int i = 1; i < size; i++)
{
    cin >> input;
    newNode->info = input; //sets newNodes first element to a new input
    newNode->next = cursor; //sets newNodes next to cursor
    cursor = newNode; //sets cursor = to newNode, so after the first run through of the loop
                      //if the user entered 1 then 2, cursor would be 2->1->0
}

您没有在此循环中为新节点分配任何空间,而是仅覆盖第一个值,这就是为什么仅打印最后一个值的原因。

同时删除最后一行:-

cursor->next = 0;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章