剑指offer--复杂链表复制

O(n)复杂度

struct node
{
    int val;
    node* next;
    node* sibling;
};
void cloneNodes(node *head)
{
    node *tmp = head;
    while(tmp!=NULL)
    {
        node *cloneNode = new node;
        cloneNode->val = tmp->val;
        cloneNode->sibling = NULL;
        cloneNode->next = tmp->next;
        tmp->next = cloneNode;
        tmp = cloneNode->next;
    }
}
void connnectSiblingNodes(nodeb* head)
{
    node *tmp = head;
    while(tmp!=NULL)
    {
        node * cloneNode = tmp->next;
        if(tmp->sibling!=MULL)
        {
            cloneNode->sibling = tmp->sibling->next;
        }
        tmp = cloneNode->next;
    }
}
node* reconnectNodes(node* head)
{
    node* newTmp=NULL;
    node* newHead = NULL;
    node* tmp = head;
    if(tmp!=NULL)
    {
        newTmp = newHead = tmp->next;
        tmp->next = newTmp->next;
        tmp = tmp->next;
    }
    while(tmp!=NULL)
    {
        newTmp->next = tmp->next;
        newTmp = newTmp->next;
        tmp->next = newTmp->next;
        tmp = tmp->next;
    }
    return newHead;
}

 

你可能感兴趣的:(算法练习)