码迷,mamicode.com
首页 > 其他好文 > 详细

裸指针对链表的相关操作

时间:2016-02-11 16:52:40      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

struct Node
{
    int value      = 0;
    Node* next = nullptr;
    Node(int value_) : value(value_) {}
};

Node* createLinkList(const std::vector<int>& data)
{
    if (data.empty()) {
        return nullptr;
    }
    auto head = new Node(data.front());
    Node* tail = head;
    std::for_each(data.cbegin() + 1, data.cend(),
        [&](int value)
    {
        tail->next = new Node(value);
        tail = tail->next;
    });
    return head;
}

void printLinkList(Node* head)
{
    while (head) {
        std::printf("%d ", head->value);
        head = head->next;
    }
}

void destroyLinkList(Node* head)
{
    if (head == nullptr) {
        return;
    }
    if (head->next) {
        destroyLinkList(head->next);
    }
    delete head;
}

Node* reverseLinkList(Node* old_head)
{
    Node* new_head = nullptr;
    while (old_head) {
        Node* next = old_head->next;
        old_head->next = new_head;
        new_head = old_head;
        old_head = next;
    }
    return new_head;
}

Node* removeDuplicates(Node* head)
{
    if (head == nullptr){
        return head;
    }
    for (auto it = head; it->next;){
        if (it->value == it->next->value){
            Node* next = it->next->next;
            delete it->next;
            it->next = next;
        }else{
            it = it->next;
        }
    }
    return head;
}

void moveHead(Node** dest_ref, Node** source_ref)
{
    auto new_head  = *source_ref;
    *source_ref    = new_head->next;
    new_head->next = *dest_ref;
    *dest_ref      = new_head;
}

void sortedInsert(Node** head_ref, Node* new_node)
{
    Node** current_ref = head_ref;
    while ((*current_ref != nullptr) &&
           (*current_ref)->value < new_node->value){
        current_ref = &((*current_ref)->next);
    }
    new_node->next = *current_ref;
    // 前一个结点保存的地址和当前结点的二级指针的解引用是同一个,
    // 都是 *current_node
    *current_ref   = new_node;
}

void insertSort(Node** head_ref)
{
    Node* new_head = nullptr;
    // 如果 for 的第三段使用 it = it->next,是不是一样呢?
    // 当然不是,因为此时的 it 已经被移动了,所以此时的 it 是在新的链表中,
    // it->next 得到的是新链表中的 next Node.
    // 所以要在 it 移动之前保留一份移动前的 next.
    for(Node* it = *head_ref, *next; it; it = next){
        next = it->next;
        sortedInsert (&new_head, it);
    }
    *head_ref = new_head;
}

 

裸指针对链表的相关操作

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/5186515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!