智能指针版本链表

class Node;
using NodePtr = std::unique_ptr<Node>;
class Node
{
public:
    int     value;
    NodePtr next = nullptr;
    explicit Node(int value_ = 0): value(value_){}
};

NodePtr create(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 print(const NodePtr& head)
{
    auto it = head.get ();
    while(it){
        std::printf("%d ", it->value);
        it = it->next.get();
    }
}

NodePtr reverse(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);
}

NodePtr merge(NodePtr& node1, NodePtr& node2)
{
    if (node1 == nullptr){
        return std::move(node2);
    }
    if (node2 == nullptr){
        return std::move(node1);
    }
    NodePtr *merged_node = nullptr;
    if (node1->value < node2->value){
        merged_node = &node1;
        (*merged_node)->next = merge (node1->next, node2);
    }else{
        merged_node = &node2;
        (*merged_node)->next = merge (node1, node2->next);
    }
    return std::move(*merged_node);
}

 

posted @ 2016-02-13 15:05  wu_overflow  阅读(614)  评论(0编辑  收藏  举报