编码链表的更好方法

Better way to code linked list?

本文关键字:方法 更好 链表 编码      更新时间:2023-10-16

我写了这个链表代码,但我无法创建单个链表,因为主函数中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/