简单链接列表插入不起作用

时间:2014-04-08 17:51:59

标签: c++ linked-list

我正在编写单链表的代码,我在编写插入函数时遇到了问题。它不是插入新节点而是不打印它们。我无法找到问题所在。任何帮助将不胜感激。

代码:

#include <iostream>

using namespace std;


class Node{
    int data;
    Node * next;

public:
    Node(int data_)
    {
        data = data_;
        next = nullptr;

    }

    void insert(int no)
    {
        Node * index = this->next;
        while (index != nullptr)
        {
            index = index->next;
        }
        index = new Node(no);
    }

    void print()
    {
        Node * index = this;
        while (index != nullptr)
        {
            cout << index->data << ", ";
            index = index->next;
        }
    }

};

int main()
{
    Node * head = new Node(1);
    head->insert(2);
    head->insert(3);
    head->insert(4);
    head->insert(5);

    head->print();

    system("pause");
    return 0;
}

由于

2 个答案:

答案 0 :(得分:1)

以下是修复代码的一种方法:

class Node{
    int data;
    Node * next;

public:
    Node(int data_, Node *ptr=nullptr) : data(data_), next(ptr) {}  
    void insert(int no) { next = new Node(no, next); }
    void print() {
        cout << data;
        if (next != nullptr)
            next->print(); 
    }
};

注意构造函数中的更改会使事情变得更好,并且还注意到目前没有析构函数,因此在定义正确的析构函数之前,这肯定会泄漏内存。

现在该程序的输出:

15432

答案 1 :(得分:0)

在我看来,你试图在列表的尾部插入新项目。您的insert中出现了一个小错误。

这是一个应该有效的版本:

void insert(int no)
{
    Node* index = this;
    while (index->next != nullptr)
    {
        index = index->next;
    }
    index->next = new Node(no);
}

代码中的错误说明

void insert(int no)
{
    Node * index = this->next;
    // When there is only one item in the linked list, which is true when
    // you are trying to insert the second item, index gets set to NULL.

    // The while loop does not get executed.
    while (index != nullptr)
    {
        index = index->next;
    }

    // index points to the newly created node but 'this' has no link
    // with index. As a consequence, 'this' never gets the second item appended
    // at the end.
    index = new Node(no);
}