标签:
class Node;
using NodePtr = std::unique_ptr<Node>;
class Node
{
public:
int value;
NodePtr next = nullptr;
explicit Node(int value_ = 0): value(value_){}
};
NodePtr createLinkedList(const std::vector<int>& data)
{
if (data.empty ()){
return nullptr;
}
auto head(std::make_unique<Node>(data.front ()));
auto tail = head.get();
std::for_each(data.cbegin () + 1, data.cend (),
[&](int value)
{
tail->next = std::make_unique<Node>(value);
tail = tail->next.get();
});
return std::move(head);
}
void printLinkedList(const NodePtr& head)
{
auto it = head.get ();
while(it){
std::printf("%d ", it->value);
it = it->next.get();
}
}
NodePtr reverseLinkedList(NodePtr& old_head)
{
NodePtr new_head = nullptr;
while(old_head){
auto next = std::move(old_head->next);
old_head->next = std::move(new_head);
new_head = std::move(old_head);
old_head = std::move(next);
}
return std::move(new_head);
}
void sortedInsert(NodePtr* head_ref, NodePtr&& node)
{
auto current_ref = head_ref;
while (((*current_ref) != nullptr) &&
((*current_ref)->value < node->value)){
current_ref = &((*current_ref)->next);
}
node->next = std::move(*current_ref);
(*current_ref) = std::move(node);
}
void insertSort(NodePtr* head_ref)
{
NodePtr new_head = nullptr;
for (NodePtr it = std::move(*head_ref), next; it; it = std::move(next)){
next = std::move(it->next);
sortedInsert (&new_head, std::move(it));
}
*head_ref = std::move(new_head);
}
NodePtr removeDuplicates(NodePtr& head)
{
if(head == nullptr){
return std::move(head);
}
for(auto it = head.get (); it->next;){
if(it->value == it->next->value){
auto next = std::move(it->next->next);
it->next = std::move(next);
}else{
it = it->next.get();
}
}
return std::move(head);
}
标签:
原文地址:http://www.cnblogs.com/wuOverflow/p/5187652.html