C++ 编写链表的更好方法?
我编写了这个链表代码,但我无法创建一个链表,因为main函数中nodeValue的内存位置所指向的值不断变化,这反过来又会改变head和tail值。我通过创建一个节点对象arraylike nodeValue[5]并传递值来解决这个问题,但这将限制为5个值。有没有一种方法可以在不使用对象数组的情况下高效地进行编码C++ 编写链表的更好方法?,c++,linked-list,C++,Linked List,我编写了这个链表代码,但我无法创建一个链表,因为main函数中nodeValue的内存位置所指向的值不断变化,这反过来又会改变head和tail值。我通过创建一个节点对象arraylike nodeValue[5]并传递值来解决这个问题,但这将限制为5个值。有没有一种方法可以在不使用对象数组的情况下高效地进行编码 #include<iostream> #include<string> using namespace std; class Node { public:
#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++中,可以使用列表库…
您已经学习过新关键字了吗?您需要学习动态内存分配。从这里开始:有没有一种有效的方法来编写代码而不使用对象数组-std::forward_list。还有,为什么main应该知道关于节点的任何信息?这就是链表的工作,它要找出使用节点的内容、位置、时间和方式。主程序应该做的就是将这个整数添加到列表中;将nodeValue作为指针传递,工作正常,我能够创建一个工作的链表。我还读到使用heap不是推荐的方法,如果我错了,请纠正我。我的更改正确吗@Drop@PremsaiG很难说没有看到整个代码。如果它适合您或满足规格/任务,则它是正确的。请注意,正如PaulMcKenzie所说,通常我们不会向用户公开列表中的节点。i、 我会在函数中隐藏节点分配。您可能需要查看的接口,以了解一个好的接口。如果您有特定的问题,请将其作为另一个问题发布。不要忘记使用调试器和添加