我从你问题中链接的教程中的代码开始,做了一些修改。请注意,这并不是更“现代”的实现方法,但它可能是理解一些相关机制的起点。
#include <iostream>
#include <initializer_list>
class LinkedList;
class ListNode
{
int data_ = 0;
ListNode *next_ = nullptr;
public:
ListNode() = default;
ListNode(int a)
: data_(a) {};
// I added this constructor, it should ease the insertions
ListNode(int a, ListNode *n)
: data_(a), next_(n) {};
friend class LinkedList;
};
class LinkedList{
private:
ListNode *first_ = nullptr;
public:
LinkedList() = default;
// I didn't want to write down your example as a bunch of list.add(42)...
LinkedList(std::initializer_list<int> lst)
{
for (auto i : lst)
add(i);
}
// Just to make the code more readable
bool is_empty() const noexcept
{
return first_ == nullptr;
}
// Only a small set of function are implemented
void add(int a);
void print();
void clear();
// The tutorial didn't implement a destructor, but you should study about RAII
~LinkedList()
{
clear();
}
};
int main()
{
LinkedList a {
41, 34, 74, 87, 33, 25, 69, 75, 85, 30, 79, 61, 38, 49, 73, 64, 57, 95, 61, 86
};
a.print();
}
void LinkedList::add(int a)
{
if (is_empty())
{
first_ = new ListNode(a);
}
else if (first_->data_ >= a)
{
first_ = new ListNode(a, first_);
}
else
{
ListNode *current = first_;
while ( current->next_ && current->next_->data_ < a )
{
current = current->next_;
}
current->next_ = new ListNode(a, current->next_);
}
}
void LinkedList::print()
{
if (is_empty())
{
std::cout << "List is empty.\n";
}
else
{
std::cout << first_->data_;
for ( ListNode *current = first_->next_; current != nullptr; current = current->next_)
{
std::cout << ", " << current->data_;
}
std::cout << '\n';
}
}
void LinkedList::clear()
{
for (ListNode *current = first_, *next; current; current = next)
{
next = current->next_;
delete current;
}
first_ = nullptr;
}
它是可测试的
here
,输出值
25, 30, 33, 34, 38, 41, 49, 57, 61, 61, 64, 69, 73, 74, 75, 79, 85, 86, 87, 95