[Question] P187 Sword refers to offer: Interview Question 36: Binary search tree and doubly linked list

Interview Question 36: Binary Search Tree and Doubly Linked List
Enter a binary search tree and convert the two search trees into a sorted doubly linked list.
It is required that no new nodes can be created, and only the point of the node pointer in the tree can be adjusted.

Leetcode link: https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/submissions/

class Solution
{
    
    
public:
    Node* copyRandomList(Node* head)
    {
    
    
        if(head==NULL)
            return NULL;
        CloneNodes(head);
        ConnectSiblingNodes(head);
        return ReconnestNodes(head);
    }

    void CloneNodes(Node* head)
    {
    
    
        if(head==NULL)
            return;
        Node* node = head;
        while(node)
        {
    
    
            Node* cnode = new Node(node->val);
            cnode->next = node->next;
            node->next = cnode;
            node = cnode->next;
        }
    }

    void ConnectSiblingNodes(Node* head)
    {
    
    
        if(head==NULL)
            return;
        Node* node = head;
        while(node)
        {
    
       
            Node* cnode = node->next;
            if(node->random)
            {
    
    
                cnode->random = node->random->next;
            }
            node = cnode->next;
        }
    }

    Node* ReconnestNodes(Node* head)
    {
    
    
        if(head==NULL)
            return NULL;
        Node* node = head;
        Node* cnode = NULL;
        Node* chead = NULL;
        if(node)
        {
    
    
            cnode=chead=node->next;
            node->next=cnode->next;
            node=node->next;
        }

        while(node)
        {
    
    
            cnode->next = node->next;
            cnode = cnode->next;
            node->next = cnode->next;
            node = node->next;
        }

        return chead;
    }
};

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/115035784