编码链表的更好方法
Better way to code linked list?
我写了这个链表代码,但我无法创建单个链表,因为主函数中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/
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 有没有更好的方法对C++中的三个整数进行排序?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 更好的方法,而不是在C ++中使用cin.ignore
- 用 c++ 为游戏制作"bullet"的更好方法?
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 做一个unordered_multimap键的平均值是更好的方法吗?
- 有没有更好的方法可以使用特征/C++实现 matlab 的逻辑索引?
- 在CMakeLists中包含目录的更好方法.txt
- 有没有更好的方法来为C++写这个?
- 有没有更好的方法来编写这个c++代码
- 将QDomDocument数据用作文本的更好方法
- 有没有更好的方法可以让我接收这些输入?C++
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 哪种方法更好获取静态链接DLL的模块句柄(HMODULE) - 使用GetModuleHandleEx()或LoadLibrary()?
- 静态常量成员值与成员枚举:哪种方法更好以及为什么?