循环将节点的实例插入到双向链表中

时间:2017-04-17 01:32:43

标签: c++ linked-list nodes

我实现代码的方式在编译时不会抛出任何错误,但是没有达到我想要的结果,这导致我相信节点没有正确链接。显示功能不断抛出“链表空了!”即使add函数正确地在控制台上显示我想要它的逻辑。在没有正确链接这些节点的add函数循环中我做错了什么?

void List::Add()
    {
        cout << "[Add]~\n";
        int I = 0;
        while (I < maxSize)
        {
            Node createdNode = new node;
            createdNode->next = NULL;
            createdNode->data = initialArray[I];
            if(!startList)//no list
            {
                createdNode->prev = NULL;
                createdNode->next = current;
                startList = createdNode;
            }
            else //there is a list
            {
                current = startList;
                while (current->next != NULL)
                {
                    current = current->next;
                } //while not at end of list, current pointer is advanced until last node is reached
                current->next = createdNode;
                createdNode->prev = current;
            }
            cout << "[" << createdNode->data << "]";
            I++;
        }
        cout << "\nHave Been Added To The Linked List!\n\n";
    }


void List::Display()
{
    cout << "[Display]~\n";
    if (!startList) //no list
    {
        cout << "Linked List Is Empty!\n\n";
    }
    else //there is a list
    {
        current = startList;
        while (current->next)
        {
            cout << "[" << current->data << "]";
            current = current->next;
        }
    }
}//void display();

#pragma once
class List
{
public: //this is where functions go
    void Length();
    void Add();
    void Display();
    void GetFile();
    void Directions();
    void Sort();

private:
    typedef struct node
    {
        int data;
        node *next;
        node *prev;
    }*Node;

    Node startList = NULL;
    Node current = NULL;
};

0 个答案:

没有答案