双链表插入无限循环... C ++

时间:2013-08-23 20:27:37

标签: c++ pointers linked-list doubly-linked-list

我在C ++中实现双向链表。在插入之前,我的打印节点功能运行良好,但在我插入前面后,打印将永远进行。

例如,我有1,2,3个数据的节点,我将数据插入前面5.然后我尝试打印,它只显示5,1,INFINITE LOOP,甚至没有进入第三个节点2

这是我的结构。

    struct dl_node
    {
        int               data;
        struct dl_node*   prev;
        struct dl_node*   next;

        dl_node(dl_node* prev, dl_node* next, int data)
        {
            // here, prev is the parameter
            // this->prev is from an object
            this->prev = prev;
            this->next = next;
            this->data = data;
        }

        // constructor, without pointer parameter
        explicit dl_node(int data)
        {
            this->prev = this;
            this->next = this;
            this->data = data;
        }
    };

这是我的插入功能。

    // "push-front" operation
    dl_node* insert_node(dl_node* head, int data)
    {
        if (nullptr == head)
                    return new dl_node(data);

            auto insertion
            = new dl_node(head->prev, head, data);
            // previous node of this insertion is head's prev
            // next node of this insertion is head

            insertion->prev->next = insertion;
            insertion->next->prev = insertion;

            return insertion;
    }

这是我的初始化。

    struct dl_node* head   = new dl_node(NULL);
    struct dl_node* node_1 = new dl_node(NULL);
    struct dl_node* node_2 = new dl_node(NULL);

    head  ->data = 1;
    head  ->next = node_1;
    node_1->prev = head;

    node_1->data = 2;
    node_1->next = node_2;
    node_2->prev = node_1;

    node_2->data = 3;
    node_2->next = nullptr;

这是我的插入内容。

    // we insert to FRONT
    head = insert_node(head, 5);

这是我的打印循环。

struct dl_node* current_node_2 = head;
while ( current_node_2 != nullptr )
    {
            cout << current_node_2->data << ", ";
            current_node_2 = current_node_2->next;
    }
    // 5, 1, I get infinite loop from here....

有人有任何想法吗?

2 个答案:

答案 0 :(得分:1)

问题是,您的默认dl_node构造函数会将prevnext都设置为this

当您致电insert_node(head, 5)时,您最终会遇到以下状态:

insertion->prev = head->prev;  // assigned in constructor, but head->prev == head
insertion->next = head;
insertion->prev->next = insertion;
insertion->next->prev = insertion;

insertion->prev == head->prev,我们知道head->prev == head,所以

insertion->prev->next = insertion

缩减为:

head->next = insertion;

所以你最终得到一个如下所示的列表:

insertion -> head -> insertion -> ...

您应该更改默认构造函数以将nextprev都设置为NULL。同样在您的插入函数中,您应该在解除引用之前检查insertion->previnsertion->next是否为非。

答案 1 :(得分:0)

我看到你所拥有的唯一真正的问题是当你做yoru插入时你正在做以下事情:

    newnode.next = head
    newnode->prev = head.prev
    newnode->data = 5

    head.prev = newnode (missing)

但是你永远不会将head.prev设置为newnode,它将使用空指针留下头部。此外,我不太清楚这段代码是什么,但它可能会错误地改变你的指针。

    insertion->prev->next = insertion;
    insertion->next->prev = insertion;