繁体   English   中英

编码链表的更好方法?

[英]Better way to code linked list?

我写了这个链表代码,但我无法创建单个链表,因为 main 函数中 nodeValue 的内存位置指向的值不断变化,这反过来又改变了头和尾值。 我通过创建一个 Node 对象数组((如 nodeValue[5])并传递值来解决这个问题,但这限制为 5 个值。有没有一种方法可以在不使用对象数组的情况下对其进行有效编码?

#include<iostream>
#include<string>

using namespace std;

class Node
{
public:
    int value;
    Node *nextNodePointer;
};

class linkedList
{
private:
    int count = 0;
public:
    Node *Head;
    Node *Tail;
    void AddNodeAfter(Node *);
    //void removeNodeAfter(Node *);
    void displayValues();
};

void linkedList::AddNodeAfter(Node *temp)
{
    if (this->count == 0)
    {
        Head = temp;
        Tail = temp;
        count++;
    }

    else
    {
        Tail->nextNodePointer = temp;
        Tail = temp;
        count++;
    }
}



Node createNodeObjects()
{
    cout<< endl << "Enter integer value :";
    Node temp;
    cin >> temp.value;
    temp.nextNodePointer = NULL;
    return temp;
}

void linkedList::displayValues()
{
    if (count == 0)
    {
        cout << endl << "Nothing to display";
    }

    else
    {
        Node value;
        value = *Head;
        for (int i = 1; i <= count; i++)
        {
            cout << endl << "Value: " << value.value;
            value = *value.nextNodePointer;
        }
    }
}

int main()
{
    cout << "Creating basic linked list" << endl;
    linkedList LinkedList;
    Node nodeValue;
    while (1)
    {
        cout << endl << "Do you want to add a value to Node ?<Y/N> : ";
        char choice;
    cin >> choice;
    if (choice == 'Y')
    {
        nodeValue = createNodeObjects();
        LinkedList.AddNodeAfter(&nodeValue);
    }
    else
        if (choice == 'N')
        {
            LinkedList.displayValues();
            break;
        }
        else
            cout << "Wrong choice" << endl;

}
}

在 C++ 中,您可以使用列表库... http://www.cplusplus.com/reference/list/list/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM