为了练习在 C++ 中使用指针(来自 C# 的经验),我决定尝试编写自己的链表类。然而,使用类和对象似乎做了一些我不理解的古怪行为。
class Node
{
public:
int value;
Node* Next = NULL;
Node(int Value)
{
this->value = Value;
this->Next = NULL;
}
};
class LinkedList
{
public:
Node* Head = NULL;
Node* Current = NULL;
int count = 0;
LinkedList()
{
Node n(-1);
Head, Current = &n;
}
void pushNode(int value)
{
//Did try stuff here, but display() caused issues.
}
void display()
{
Node* curr = Head;
cout << "HEAD->";
while(curr->Next != NULL)
{
curr = curr->Next;
cout << curr->value << "->";
}
cout << "NULL";
}
};
int main() {
LinkedList ml;
ml.pushNode(10);
ml.display();
return 0;
}
运行此代码后,“HEAD->”被写入控制台,然后程序结束。如果我将一个项目添加到列表中,控制台将被无休止地发送任何值的垃圾邮件。帮助!
C# 使用垃圾收集,减轻了程序员对管理内存的很多顾虑。
C++ 不提供垃圾回收,因此程序员需要注意管理对象的内存及其生命周期。现代 C++ 提供智能指针和容器来帮助管理内存和对象生命周期。
#include <iostream>
#include <memory>
#include <utility>
using std::cout;
using std::make_unique;
using std::move;
using std::ostream;
using std::unique_ptr;
class Node {
public:
int value{};
unique_ptr<Node> next;
Node(int value_, unique_ptr<Node> next_) : value{value_}, next{move(next_)} { }
};
class LinkedList {
public:
unique_ptr<Node> head;
LinkedList() { }
void pushNode(int value) {
auto node{ make_unique<Node>(value, move(head)) };
head = move(node);
}
void display(ostream& out) {
Node* curr = head.get();
out << "HEAD->";
while (curr) {
out << curr->value << "->";
curr = curr->next.get();
}
out << "null\n";
}
};
int main() {
LinkedList ml;
ml.pushNode(10);
ml.pushNode(20);
ml.pushNode(30);
ml.display(cout);
}
谢谢大家!我已经解决了您的意见并做了更多的研究,结果如下。
#include <iostream>
using namespace std;
class Node
{
public:
int value;
Node* Next = nullptr;
Node(int data)
{
value = data;
}
};
class LinkedList
{
private:
Node* Head = nullptr;
Node* Current = nullptr;
int count = 1;
public:
LinkedList(int data)
{
Head = new Node(data);
Current = Head;
}
void push(int value)
{
Node* n = new Node(value);
Current->Next = n;
Current = n;
count++;
}
void pop()
{
if(count > 1)
{
Node* Temp = Head;
Head = Head->Next;
delete Temp;
}
}
void printList()
{
Node* curr = Head;
cout << "HEAD->" << curr->value << "->";
while(curr->Next != nullptr)
{
curr = curr->Next;
cout << curr->value << "->";
}
cout << "NULL" << endl;
}
};
int main() {
LinkedList ml(10);
ml.push(10);
ml.push(20);
ml.printList();
ml.pop();
ml.printList();
return 0;
}